Initially I was using just TextWriter iterationLogger = new StreamWriter(Iteration log.txt");
which works fine, but I wanted to add a timestamp to the file and tried this:
TextWriter iterationLogger = new StreamWriter($"{DateTime.Now} Iteration log.txt");
Then StremWritter throws "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?
>Solution :
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.