I want to specify a virtual path of a file but I am not able to do so.
Here is my code:
int Course_Id = 1;
int PortfolioID=1;
int ChandidateID=1;
string filepath = Server.MapPath("~/ePortfolio/PortFolioContent/" + Course_Id + "/Assignments/Exhb_" + item.PortfolioID + "_" + item.ChandidateID + ".jpg");
if(System.IO.File.Exists((filepath)))
{
ViewBag.Thumbnail = filepath;
}
When i use Server.MapPath it is fetching data from some other path:
My original path is:
E:\HOBBYHOMES(E-PORTFOLIO)\HobbyHomesWebApp\ePortfolio\PortFolioContent\1\Assignments
but it is taking this path
E:\HOBBYHOMES(E-PORTFOLIO)\HobbyHomesWebApp\ActivityPostin\Images\ePortfolio\PortFolioContent\1\Assignments\Exhb_1_1.jpg
I m not understanding why this is workin so.Please help me
Try string filepath = Server.MapPath("~/... ...jpg");
You can use #Url.Content("~/Content/Images/YourImageName.png")
Try doing something like this:
Path.Combine(Server.MapPath("~/"),("ePortfolio\\PortFolioContent\\" + Course_Id + "\\Assignments\\Exhb_" + item.PortfolioID + "_" + item.ChandidateID + ".jpg"));
In theory it results in the same answer that failed you previously. In practice, it may yield a completely different answer.
There's also a recent question here (which I can't find at the moment) which highlights that sometimes Server.MapPath("~/..etc..") misbehaves on rewritten request paths. Are you rewriting the request that is trying to form this path?
Related
I have been trying to make a program and it saves mechanics invoices. So I have got this far;
oWord.Application.ActiveDocument.SaveAs2("C:/BMW/Invoices/" + Regbox.Text + "/thing.doc");
which saves the word doc in a folder that is specified by the registration of the bike - this works fine. but what I really want is the date to be used as a filename...I couldn't figure that out, so I made a date label and plan on using the text from it as the filename instead (I know, its a long way round...but it works). Anyways, I have tried;
oWord.Application.ActiveDocument.SaveAs2("C:/BMW/Invoices/" + Regbox.Text + "/" + label19.Text + ".doc");
this was an "invalid filename"
oWord.Application.ActiveDocument.SaveAs2("C:/BMW/Invoices/" + Regbox.Text + "/label19.Text.doc");
this saved it as "label19.Text.doc"
oWord.Application.ActiveDocument.SaveAs2("C:/BMW/Invoices/" + Regbox.Text + "/" + label19.Text, ".doc");
This threw the error "(DISP_E_TYPEMISMATCH)"
All I need to do is get label19 text to work as a filename with a .doc extension...or another way of getting the date as a filename
If you need to use current date as file name then you can use:
oWord.Application.ActiveDocument.SaveAs2("C:/BMW/Invoices/" + Regbox.Text + "/" + DateTime.Now.ToString("MM-dd-yyyy") + ".doc")
Generate the file name in an string variable:
string filename = "C:/BMW/Invoices/" + Regbox.Text + "/" + DateTime.Now.ToString("MM-dd-yy");
and then pass it to SaveAs2 method:
oWord.Application.ActiveDocument.SaveAs2(filename, ".doc");
I am trying to move multiple files in a directory to an archive sub folder. I used a foreach loop to do the idea. Unfortunately, It can only move a file if there is only one file in the directory. But when I put multiple in the directory the Directory.move(); won't work. Can anyone help me?
static string antJsonSerializer(){
#region KDI SALES
string[] allfiles = Directory.GetFiles(#"C:\xml\"); // Put all file names in root directory into array.
string sourceDirectory = #"C:\xml\";
string destinationDirectory = #"C:\xml\Archive\";
// Check if directories are existing -- Working
bool xmlRoot = System.IO.Directory.Exists(sourceDirectory);
if (!xmlRoot) System.IO.Directory.CreateDirectory(sourceDirectory);
bool xmlArchive = System.IO.Directory.Exists(destinationDirectory);
if (!xmlArchive) System.IO.Directory.CreateDirectory(destinationDirectory);
AntHelpers drone = new AntHelpers();
foreach (string name in allfiles)
{
try
{
drone.xmltosql(#name.Trim());
//File.Move(#name, destinationDirectory + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html"); //Not working
Directory.Move(#name, destinationDirectory + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");
//Directory.Move(sourceDirectory, destinationDirectory); //Not working
}
catch (Exception e)
{
//Console.WriteLine("Main Process Catch ERR: " + e.Message);
//ErrLogtoDB(string TRNTYPE, string extserial, string texttowrite, string logfilename)
AntHelpers.ErrLogtoDB("SALES", #name, "Ant JSON Serializer Failed: " + e.Message,
"LeafCutterLogFile_JSONSerializer_" + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");
}
//drone.ExtractSQLSendAntHill(); //For testing: OFF
#endregion
return " !!!! Work Complete !!!! ";
}
You are trying to save a file with year + month + day + hour.html as "NAME". If multiple files are there, then how can you save it with same file name? Instead you should add seconds and/or milliseconds, or use something else to distinguish the file and make it a unique name. Otherwise, take file name without the extension then add year, month, day, and hour. That is why you are not able to move multiple files at a time, because when try to move the second file an exception will be thrown say "unable to move an existing file."
Directory.Move takes a source and destination directory, not a file path. Try this:
Directory.Move(sourceDirectory, destinationDirectory);
Also, it can be run at the very end - after the foreach loop.
I have three dropdown lists. From these three I have to select various path to retrieve one folder. The problem is path can't retrieve the folder and give error can't find a part of path. My code for that is.
protected void Btn_Load_Click1(object sender, EventArgs e)
{
string _username = ConfigurationManager.AppSettings["ImpersonatedUserName"].ToString();
string _password = ConfigurationManager.AppSettings["ImpersonatedPassword"].ToString();
string _domain = ConfigurationManager.AppSettings["ImpersonatedDomain"].ToString();
Impersonation objImpersonation = new Impersonation();
if (objImpersonation.impersonateValidUser(_username, _domain, _password))
{
string PathFecha = ConfigurationManager.AppSettings.ToString() + "\\Convert.ToString(Drp_List1.SelectedItem)\\Convert.ToString(Drp_List2.SelectedItem)\\Convert.ToString(Drp_List3.SelectedItem)\\";
string[] files = System.IO.Directory.GetFiles(PathFecha);
foreach (string filename in files)
{
ListBox1.Items.Add(new ListItem(System.IO.Path.GetFileName(filename), filename));
}
}
}
You are not converting the paths properly.
Change this line:
string PathFecha = ConfigurationManager.AppSettings.ToString() + "\\Convert.ToString(Drp_List1.SelectedItem)\\Convert.ToString(Drp_List2.SelectedItem)\\Convert.ToString(Drp_List3.SelectedItem)\\";
TO:
string PathFecha = string.Format("{0}{4}{1}{4}{2}{4}{3}{4}", ConfigurationManager.AppSettings.ToString(), Drp_List1.SelectedText, Drp_List2.SelectedText, Drp_List3.SelectedText, "\\");
Use Drp_List1.SelectedItem.Text if you need Text of selected dropdown menu item.
Use Drp_List1.SelectedItem.Value if you need Value of selected dropdown menu.
Do this for all dropdowns.
string PathFecha =
System.IO.Path.Combine(
ConfigurationManager.AppSettings.ToString(),
Drp_List1.SelectedItem.Text,
Drp_List2.SelectedItem.Text,
Drp_List3.SelectedItem.Text);
Using Path.Combine() may make it a little easier dealing with the paths.
Well it looks to me that with this line:
string PathFecha = ConfigurationManager.AppSettings.ToString() + "\\Convert.ToString(Drp_List1.SelectedItem)\\Convert.ToString(Drp_List2.SelectedItem)\\Convert.ToString(Drp_List3.SelectedItem)\\";
you are simply concatenating a single string to the base path, which is not what you want. Putting C# code into a string won't replace the result of that code in the string. What you want to do is concatenate each part of the path individually:
string PathFecha = Convert.ToString(Drp_List1.SelectedItem) + "\\"
+ Convert.ToString(Drp_List2.SelectedItem) + "\\"
+ Convert.ToString(Drp_List3.SelectedItem) + "\\";
And, as Gloria said, if you want to use the text of the selected item, you should use Drp_List1.SelectedItem.Text. So it should actually be:
string PathFecha = Drp_List1.SelectedItem.Text + "\\"
+ Drp_List2.SelectedItem.Text + "\\"
+ Drp_List3.SelectedItem.Text + "\\";
I don't know what is wrong with the following string:
"Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
I can't get the concatenated string. I am getting Report(29-Dec-2009. That's all and
the rest gets left out from the string.
What is the reason?
Try this:
string filename =
String.Format(
"Report({0:dd-MMM-yyyy} to {1:dd-MMM-yyyy})",
System.DateTime.Now, System.DateTime.Now.AddMonths(-1));
EDIT: Since in your download box you got your filename broken in first whitespace, you could to try ONE of these:
filename = HttpUtility.UrlEncode(filename); // OR
filename = """" + filename + """";
Seems some browsers doesn't handles whitespaces very nicely: Filenames with spaces are truncated upon download. Please check it you can to download other filenames with whitespace in other sites.
You need to assign it to something:
string s = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
Update: I just saw your update to the question. How are you displaying the string? I'm guessing that you are displaying it in a GUI and the label is too short to display the complete text.
Try this:
string newstring =
string.Format(
"Report ({0} to {1})",
System.DateTime.Now.ToString("dd-MMM-yyyy"),
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
);
What are you assigning the result to? It would be easier to read the code if you used string.Format
You are not assigning the concatenated result to anything, so can't use it:
string myConcatenated = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + ")";
Using this code...
string test = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " +
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")";
I saw the following result.
Report(29-Dec-2009 to 29-Nov-2009)
It could be that the string is being truncated later on. Make sure that you set a breakpoint right after this code is run and check the value of the variable to which it is assigned (test in my case).
If, as in your previous question, you are using this value to create a file, it may be that it's the space before "to" that is causing the problem. Try to use:
"Report("
+ System.DateTime.Now.ToString("dd-MMM-yyyy")
+ "To"
+ System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
+ ")"
instead and see if that fixes it.
If that does fix it, you'll probably need to either figure out how to quote the entire file name so it's not treated as the three separate arguments, "Report(29-Dec-2009", "to" and "29-Nov-2009)". Or simply leave your reports names without spaces.
I'd choose the latter but then I'm fundamentally opposed to spaces in filenames - they make simple scripts so much harder to write :-)
I am doing Image uploader in Asp.net and I am giving following code under my controls:
string st;
st = tt.PostedFile.FileName;
Int32 a;
a = st.LastIndexOf("\\");
string fn;
fn = st.Substring(a + 1);
string fp;
fp = Server.MapPath(" ");
fp = fp + "\\";
fp = fp + fn;
tt.PostedFile.SaveAs("fp");
But during uploading or saving image the error message comes that The SaveAs method is configured to require a rooted path, and the path 'fp' is not rooted.
So Please help me what is the problem
I suspect the problem is that you're using the string "fp" instead of the variable fp. Here's the fixed code, also made (IMO) more readable:
string filename = tt.PostedFile.FileName;
int lastSlash = filename.LastIndexOf("\\");
string trailingPath = filename.Substring(lastSlash + 1);
string fullPath = Server.MapPath(" ") + "\\" + trailingPath;
tt.PostedFile.SaveAs(fullPath);
You should also consider changing the penultimate line to:
string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
You might also want to consider what would happen if the posted file used / instead of \ in the filename... such as if it's being posted from Linux. In fact, you could change the whole of the first three lines to:
string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
Combining these, we'd get:
string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
tt.PostedFile.SaveAs(fullPath);
Much cleaner, IMO :)
Use Server.MapPath():
fileUploader.SaveAs(Server.MapPath("~/Images/")+"file.jpg");
If you want to save the uploaded file to the value of fp, just pass it in, don't put it in quotes:
tt.PostedFile.SaveAs(fp);
When reading the title of the question, I was thinking that it looked like you had put quotation marks around the variable name. Not really believing that it was so, I opened the question to read it, but it really was so...
We cannot use the "SaveAs" method to write directly to an FTP server.
Only local paths and UNC paths are supported for the above method.
To save it to FTP, please use the FtpWebRequest class.
You will get the full details to this in the same type of question answer in social.msdn.
Please go through the link.. and you will be able to solve the issue..
enter link description here
--thanks for the answer by Jesse HouwingXPirit (MCC, Partner, MVP)
I encountered the same problem. The problem is that you did not specify the path of the server that you want the file to be saved. And here is a probably simpler answer:
string fileName = tt.PostedFile.FileName;
string savePath = Server.MapPath("Path/Of/The/Folder/Comes/Here/") + fileName);
tt.PostedFile.SaveAs(savePath);