Writing to text file with specific date and time in the file name

11,439

Solution 1

You might want to make sure that the path is valid and the datetime string does not contain invalid characters:

string time = DateTime.Now.ToString("yyyy-MM-dd"); 

  // specify your path here or leave this blank if you just use 'bin' folder
string path = String.Format(@"C:\{0}\YourFolderName\", time);

string filename = "test.txt"; 

// This checks that path is valid, directory exists and if not - creates one:
if(!string.IsNullOrWhiteSpace(path) && !Directory.Exist(path)) 
{
   Directory.Create(path);
}

And finally write you data to a file:

File.WriteAllText(path + filename,"HelloWorld");

Solution 2

According to the MSDN a DateTime.Now.ToString("d") looks like this: 6/15/2008(edit: depending on your local culture it could result in a valid filename)

Slashes are not valid in a filename.

Solution 3

replace

string time = DateTime.Now.ToString("d");
File.WriteAllText(time+name+"test.txt","HelloWorld");

with

string time = DateTime.Now.ToString("yyyyMMdd_HHmmss"); // clean, contains time and sortable
File.WriteAllText(@"C:\yourpath\" + time+name + "test.txt","HelloWorld");

you have to specify the whole path - not just the filename

Solution 4

This is because your name would be resolving to "7/29/2015MyNametest.txt" or something else which contains an invalid character depending on the culture of your machine. The example that I gave is obviously not a valid file path. We have to remove the slashes (/). They are not allowed in file name on Windows.

See this question as a comprehensive file naming guideline on Windows and Linux.

Share:
11,439
Naughty Ninja
Author by

Naughty Ninja

Updated on June 09, 2022

Comments

  • Naughty Ninja
    Naughty Ninja almost 2 years

    I am trying to write all my data to a text file and it is working unless I put DateTime in the file name.
    The current code looks like this:

    string time = DateTime.Now.ToString("d");
    string name = "MyName";
    File.WriteAllText(time+name+"test.txt","HelloWorld");
    

    I am getting this exception:

    An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll

    But as far as I know, the File.WriteAllText() method should create a new file or overwrite already existed file.

    Any suggestions?