Path format is illegal - c#

I want to ask about a easy question , but I faced a problem.
I want to get the time when the program is executed
Console.WriteLine(DateTime.Now);
And I want to output a .log file , the file name will have program execution time
String path2 = "C:\\temp"+DateTime.Now+".log";
StreamWriter path = File.CreateText(path2);
path.WriteLine(DateTime.Now);
But it is telling me Path format is illegal.
And I want ask another question
string a12 = aaa.Element("a12").tostring();
String path2 = "C:\\temp" + a12.ToString + ".log";
But it tell me "Path format is illegal"
How can I resolve it?
Thanks

That's because DateTime.Now converted to string by default contains time information (e.g. 8:53). Semicolon is illegal in path name.
If you meant only date to be in your file name, you could use:
String path2 = "C:\\temp" + DateTime.Now.ToString("d") + ".log";
(Edit) For some cultures this still can lead to invalid values, so as others pointed out, it is best to use explicit formatter:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";

You want to escape your \ in the "" quoted string, and also there are characters in the result of DateTime.Now that cannot be in paths. You'll need to escape/replace those as well.

When you put DateTime.Now into a path, you risk adding characters that aren't valid as a path (like the : separator. That is the reason you get this error message.
You could replace it with a .:
string path2 = Path.Combine
( #"C:\temp\"
, DateTime.Now.ToString("yyyy-MM-dd.HH24.mm.ss")
, ".log"
);

DateTime.Now probably contains illegal characters depending on your local system settings. To get a valid and consistent file name independent on the culture the system is installed in you should create the log file name by hand, for instance like this:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";

String path2 = String.Format("C:\\temp{0}.log", DateTime.Now.ToString("yyyyMMdd"));
Since filename cannot take "/" which was created by DateTime.Now.ToString("d") and hence creating issue.

Related

System.NotSupportedException : 'The format of the given path is not supported.' C#

For searching files in a directory, I am using this snippet of code :
string targetToCopy = ConfigurationManager.AppSettings["drive"] + element.Element("categorie").Value.ToString().Replace(" / ", #"\");
DirectoryInfo directoryToCopy = new DirectoryInfo(targetToCopy);
I create the path with this string targetToCopy, I parse the string in DirectoryInfo for using the directoryToCopy.GetFiles() method.
This method searches files with path, and when I use this in my loop, I get an error:
System.NotSupportedException : 'The format of the given path is not supported.'
I don't know what this error means, but if you know how to solve the problem.
Thank you and good luck :)
I determined the problem by outputting my path to a log file, and finding it not formatting correctly. Correct for me was quite simply:
DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.FullName.ToString());
There is a space before the / in Replace(" / ", #"\") therefore String.Replace transformation is not in effect
Updated code
string targetToCopy = ConfigurationManager.AppSettings["drive"] + element.Element("categorie").Value.ToString().Replace("/ ", #"\");

Remove Extra back slash "\" from string file path in c#

How to convert
"String path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
into
String path = #"C:\Abc\Omg\Why\Me\".
My approach is to first reverse the string and then remove all the "\" till we get first char, and the reverse it again.
How to do this in C#, is there any method for such operation?
You can just construct path using the Path static class:
string path = Path.GetFullPath(#"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\");
After this operation, variable path will contain the minimal version:
C:\Abc\Omg\Why\Me\
You can use path.TrimEnd('\\'). Have a look at the documentation for String.TrimEnd.
If you want the trailing slash, you can add it back easily.
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = path.TrimEnd('\\') + '\\';
another solution is
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = Path.GetFullPath(path);

Removing file extension in asp.net

How can I remove the extension file in asp.net something like filename.jpg to filename? I tried searching some reference but all I find is URL extension only
Use the System.IO.Path.GetFileNameWithoutExtension Method
The return value for this method is the string returned by GetFileName, minus the last period (.) and all characters following it.
string fileName = Path.GetFileNameWithoutExtension(fuImage.FileName); //file-name
string fileExt = Path.GetExtension(fuImage.FileName); //.jpg,.png....
string path_thumb = Path.Combine("Images/", string.Format("{0}{1}{2}", fileName, "-" + datetime + "-thumb", fileExt)); //full path: Images/file-name-012345-thumb.jpg

The given path's format is not supported

I am trying to downlaod an excel sheet and I am dynamically generating its filename which has to be in the following format:
eg:
User_Wise_List_Of_Documents_2013_On_16_04_2013
For this I wrote the following code:
string currentDate = DateTime.Now.Date.ToString();
string currentYear=DateTime.Now.Year.ToString();
filename = Server.MapPath("~/User/Documents/") +
"User_Wise_List_Of_Documents_" + currentYear + "on" + currentDate +
".xls";
Somehow, its giving me the following exception:
The given path's format is not supported.
Any help will be appreciated.
I think your filename contains invalid chars like : Because you are forming filename with string currentDate = DateTime.Now.Date.ToString().
See the list for invalid chars
var invalidChars = Path.GetInvalidFileNameChars();
EDIT
You can use this to replace invalid chars
string newdatestr = String.Join("",currentDate.Select(c => invalidChars.Contains(c) ? '_' : c));
Have you checked the result of Server.MapPath("~/User/Documents/")?
It will return the directory path of your website's folder "/User/Documents/", which would be for example "C:\wwwroot\User\Documents\". You cant download a file from there (unless you're hosting local, in which case it might work, but for you only.
Probably you're looking for the Page.ResolveUrl() function, which will create a web uri relative to your website, rather than to the filesystem.

The SaveAs method is configured to require a rooted path, and the path 'fp' is not rooted

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);

Categories