Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create file name with current date

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;
            }
        }
like image 467
ziad mansour Avatar asked Nov 27 '25 20:11

ziad mansour


2 Answers

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

like image 119
Mathias F Avatar answered Nov 29 '25 09:11

Mathias F


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.

File Name is wrong

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(':', '-');
like image 39
RajeshKdev Avatar answered Nov 29 '25 10:11

RajeshKdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!