With the limitations that a filename provides, what is the simplest way to write a datetime into a filename and then read it back into a datetime in .net?
how about simply:
DateTime original = DateTime.Today;
string s = original.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture);
(obviously combine with the rest of the file name... add more precision as necessary - hours, minutes, etc)
EDIT: Unfortunately the original format uses colons, which can't be used in Windows filenames. That's a real shame, as it's otherwise ideal. In that case I'd go for:
yyyy-MM-dd`T`HH-mm-ss
(with milliseconds if you need them). I don't know if any cultures use anything unusual for any of those fields. That would be quite surprising, but you should probably use CultureInfo.InvariantCulture
just to be sure.
I like having the dashes in there though - it makes it easier to parse when you're looking down a list of files.
EDIT: Original answer
I suggest you use the sortable date/time format pattern given by the 's' standard format string, e.g.:
Console.WriteLine(DateTime.UtcNow.ToString("s"));
which prints something like:
2009-04-08T06:45:43
This is easy for humans to parse, easy for computers to parse, culture-independent, and sorts appropriately.