save todays date to file name

Trying to include date into a filename when the file is written.

DateTime todaysDate = DateTime.Now;
string destFile = System.IO.Path.Combine(targetPath + todaysDate.ToShortDateString() + ".dat");

Error:

 Could not find a part of the path 'C:\Users\John\Desktop\Sales\Import11/02/2014.dat'.

Possible to change date to separated by _ ? or any other suggestions to resolve this? Ta

Jon Skeet
people
quotationmark

I would suggest:

  • Using a sortable date format, just because that's naturally pleasant
  • Explicitly specifying the invariant culture, to avoid oddities of ending up using a different calendar system. (I suspect you always want to use the Gregorian calendar.)
  • Explicitly specifying delimiters which aren't going to cause problems in a file system path (which / and : do)

So something like:

string name = string.Format(CultureInfo.InvariantCulture,
                            "Import-{0:yyyy-MM-dd}.dat",
                            DateTime.Today);

// Assuming that targetPath is the directory; it's slightly unclear.
string path = Path.Combine(targetPath, name);

Note:

  • By using Today, you're using the system local time zone. That may well be what you want, but you need to consider it explicitly.
  • You're only using the date, rather than the date and time - is that definitely okay? Will you ever need to handle multiple imports on the same day?

people

See more on this question at Stackoverflow