phili
phili

Reputation: 385

How do I create a file based on the date?

    string filename = DateTime.Today.ToString() + ".csv";
    if(!File.Exists(filename))
        File.Create(filename);

I thought this would work but it throws a 'format not supported' error. I just want a csv to be created in the directory alongside my .exe

Upvotes: 1

Views: 1472

Answers (5)

Michael Paulukonis
Michael Paulukonis

Reputation: 9100

As everybody has pointed out, the default DateTime.ToString() formatting has invalid characters in it (for just about any region settings), so that

string filename = DateTime.Now.ToString() + ".csv";

generates a 'filename' like 2/18/2011 4:26:48 PM.csv -- which is invalid

if you want a date-time based name, try

string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";

to get something like 2011021804254.csv

you can add more formatting, just as long as it doesn't contain any of the following: \ / : * ? " < > |

Upvotes: 1

Ferruccio
Ferruccio

Reputation: 100648

I think the problem is that converting a DateTime to a string will generate a string with invalid filename characters, such as colons (:) and that will cause the create to fail.

You may want to use a format string to control the generated filename. e.g.

string filename = DateTime.Today.ToString("yyyy-MM-dd") + ".csv";

Upvotes: 5

Marc Gravell
Marc Gravell

Reputation: 1062660

I'm guessing your locale has / / : (or similar confusing characters) in the date format. You should specify an explicit format - "yyyy MM dd" for example:

string filename = DateTime.Today.ToString("yyyy MM dd",
            CultureInfo.InvariantCulture) + ".csv";

Upvotes: 1

Jimmy
Jimmy

Reputation: 9815

Your date has slashes in it, try this instead

string filename = Datetime.Now.Ticks.ToString() + ".csv";

Upvotes: 0

Mark Avenius
Mark Avenius

Reputation: 13947

This is because DateTime.Today.ToString() contains slashes, which are not valid as part of a windows filename.

You can, however, do this: DateTime.Now.ToString("yyyyMMdd")

Upvotes: 3

Related Questions