C#

How to create filename containing date/time in C#

In datalogging, often you have to create a new log file once you start to log data.

In most cases, it’s convenient to include the current date and time in the log file. Here’s how you can do that in C# without using external libraries:

string filename = String.Format("Temperature logging {0}.csv",
                                DateTime.UtcNow.ToString("yyyy-MM-dd HH-mm-ss"));

This will create filenames like

Temperature log 2020-06-17 22-37-41.csv
Temperature log 2019-12-31 00-15-55.csv

Note that if you use another Date/time format, you need to avoid special characters that must not occur in filenames. The rules for which filename is correct are much easier on Linux than on Windows, but since you should be compatible with both operating systems, you should always check the Windows rules.

These characters are forbidden for Windows filenames:

<>:"/\|?*

The date-time format we used above, yyyy-MM-dd HH-mm-ss is specially crafted in order to avoid colons in ISO-8601-like date/time formats such as 2020-04-02 11:45:33 since colons would be illegal in Windows filenames. yyyy-MM-dd HH-mm-ss only contains spaces and minus (-) characters in order to avoid any issues, now and in the future.

Posted by Uli Köhler in C#