In my C# Windows Forms application I have log data. I save them in a text file, but I want to name this file with some description with the current date/Time. But while debugging the code I got this error:
The given path's format is not supported.
here's my code:
string dateAndTime = " '' " + DateTime.Now.ToShortDateString() + "-" + DateTime.Now.ToShortTimeString() + " '' ";
string sPath = @"C:/Desktop/Logs - "+ dateAndTime + ".txt";
int type = 0;
using (StreamWriter sw = File.CreateText(sPath))
{
int J = 0;
for (int i = 0; i < logsList.Count; i++)
{
if (logsList[i + 3] == "IN")
{
type = 3;
}
else if (logsList[i + 3] == "OUT")
{
type = 4;
}
sw.WriteLine(logsList[i] + " " + logsList[i + 1] + " " + logsList[i + 2] + " " + logsList[i + 3] + " " + logsList[i + 4]);
i += 4;
}
}
Use this for a format with no slashes
DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
ToShortDateString uses the current language which will result in different results depending on the machine where the code executes
Your file name format is wrong, this kind of file name formats will not be supported by the operating system.
i.e : your file name contains / and :, Which are special characters that are not supported by the operating system to name the file.
That's why you are getting the error saying
The given path's format is not supported.

Also i would suggest you to do not use the special chars like this
" '' ". Its not required there.
Use this below code if you wish this kind of file name formats C:/Desktop/Logs - 7-1-2015-3-45 PM.txt.
Sample Code for Valid File Name:
string dateAndTime = DateTime.Now.ToShortDateString() + "-" + DateTime.Now.ToShortTimeString();
dateAndTime = dateAndTime.Replace('/', '-');
dateAndTime = dateAndTime.Replace(':', '-');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With