silhouette hustler
silhouette hustler

Reputation: 1763

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

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?

Upvotes: 3

Views: 13604

Answers (4)

Steffen Winkler
Steffen Winkler

Reputation: 2864

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.

Upvotes: 5

Fabjan
Fabjan

Reputation: 13676

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

Upvotes: 8

fubo
fubo

Reputation: 45947

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

Upvotes: 3

Mayank
Mayank

Reputation: 1631

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.

Upvotes: 2

Related Questions