Search code examples
c#filedatetimefilestream

How to Create a Text Filename with DateTime using C#


I want to create a Filename with DateTime.Now to store the errors that catched using Exception Handling everyday.

I used DateTime.ToFileTime, but the format appending for not in date format.

string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
string path = "E:\\ErrorCollector\\ErrorCollector" + DateTime.Now.ToFileTime()+ ".txt";

FileStream fi = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter sw1 = new StreamWriter(fi);
sw1.WriteLine(DateTime.Now + "" + ex.message);

I am Expecting the filename like "ErrorCollector17/08/2019"


Solution

  • You can try to use ToString function with a format.

     DateTime.Now.ToString("dd/MM/yyyy",new System.Globalization.CultureInfo("en-US"));
    

    c# online

    As Soundararajan say I would suggest you use

    "ddMMyyyy"
    

    or

    "dd-MM-yyyy"
    

    due to the system will confuse your path contain \