Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

StreamWriter throws "The filename, directory name, or volume label syntax is incorrect" on a path with DateTime

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading