C# DateTime for Filenames

.NET Framework information

You want to put the date and time in a filename. There are many ways of accomplishing this, but some are clearer to read and easier to modify than others. Your requirements may be to include the date, or the date and the time.

These C# example programs demonstrate how to put a DateTime in filenames.

Dates and required filenames
    You can use DateTime formatting for filenames.

Date:              11/18/2008 5:04:44 PM
Required filename: text-2008-11-18_05-04-44-PM.bin

Date:              11/23/2004 12:05:47 AM
Required filename: text-2004-11-23-12_05-47-AM.bin

Example

Note

First we see an example of using the current date and time as the name for a file on the file system. Here we use the string.Format method, and combine it with DateTime.Now, for a method that outputs the correct string based on the date and time.

Program that uses date as filename [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	//
	// Write file containing the date with BIN extension
	//
	string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
	    DateTime.Now);
	File.WriteAllText(n, "aaa");
    }
}

Description of format string
    "text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin"

text-      The first part of the output required
	   Files will all start with text-
{0:        Indicates that this is a string placeholder
	   The zero indicates the index of the parameters inserted here
yyyy-      Prints the year in 4 digits followed by a dash
	   This has a "year 10000" problem
MM-        Prints the month in two digits
dd_        Prints the day in two digits followed by an underscore
hh-        Prints the hour in two digits
mm-        Prints the minute, also in two digits
ss-        As expected, it prints the seconds
tt         Prints AM or PM depending on the time of day

Environment.SpecialFolder example

Here we see that you can use this code with Environment.SpecialFolder. You can encapsulate the logic for this in a property accessor. In other words, you can use a property to get the complete filename easily.

Program that filename property [C#]

using System;
using System.IO;

class Program
{
    static string SpecialFileName
    {
	get
	{
	    // A
	    return string.Format("{0}{1}text-{2:yyyy-MM-dd_hh-mm-ss-tt}.bin",
		// B
		Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
		// C
		Path.DirectorySeparatorChar,
		// D
		DateTime.Now);
	}
    }

    static void Main()
    {
	Console.WriteLine(SpecialFileName);
    }
}

Output

C:\Users\Sam\Documents\text-2008-11-18_05-23-13-PM.bin
Note

Description. In part A, it uses a format string. This format string has three placeholders: first, the directory name we get from SpecialFolder, then the separator char, and finally the specially formatted DateTime. Also, it specifies the file name starts with text and ends with .bin.

Part B. It gets the My Documents folder path. This line uses the SpecialFolder.MyDocuments enum value to get the user's folder path.

Environment.SpecialFolder

Final parts. It uses Path.DirectorySeparatorChar. On Windows, this is the backslash. You could just use \\ in the string instead. It uses DateTime.Now. As expected, this returns the local time.

Format string separators

Format illustration

You can change the string separators by replacing the underscores and dashes with any other character, excluding some special ones. I haven't found many uses for separators other than dashes, underscores, and spaces. Note that filenames cannot have some characters.

Reserved Filenames

Summary

The C# programming language

Here we saw how to generate file names containing the current date in C# code. This is useful for "data dumps" and log files where daily files are written. Never use random names except when you need temporary files. It is almost always better to append the date to the file name. If you have to write files frequently, the "ss" field can help.

Time Representations
.NET