-1

I wanted to add a timestamp to the writing file and tried this:

TextWriter iterationLogger = new StreamWriter($"{DateTime.Now} Iteration log.txt");

Then StremWritter throws exception The filename, directory name, or volume label syntax is incorrect

I tried various arguments (append, encoding, @, $) and formats, e.g. string.Format("{0} Iteration log.txt", DateTime.Now) but the problem is still there.

As far as I understood, with just a string StreamWritter creates the file right inside the program folder, but something changed with the addition of DateTime inside the string that prevents file creation?

Update 16/03/2023

For any future reader - please check this reference: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

Humble Newbie
  • 98
  • 1
  • 11
  • 3
    An example of `DateTime.Now` is `2/28/2023 4:17:08 PM`. `:` is not valid in filenames, and `/` is a directory separator (and you probably don't want a directory called `2` or `28`...) – canton7 Feb 28 '23 at 16:18
  • 1
    Please re-read the [mre] guidance on posting code and show all necessary information inline in the code. In particular there are two unrelated problems that you seem to be solving - why StreamWriter fails - if that is the one you are interested in you should remove all formatting from the sample and just show final string inline in the code like `new StreamWriter("2/28/2023 ...")` and explain what you expect that code to do (probably creating folders for you?). The second variant of the question is "format datetime for file name" is unlikely as it is asked too many times... – Alexei Levenkov Feb 28 '23 at 17:01

1 Answers1

2

Using DateTime.Now like this uses the default ToString() implementation of DateTime, which results in something like 28.02.2023 17:21:45 (also depending on your regional settings). However, colon is generally not allowed in file or directory names. You can use something like $"{DateTime.Now:yyyy-MM-dd_HH-mm}" instead, for example.

t.haeusler
  • 76
  • 5