Dot Net Perls

Use DateTime for Filenames - C#

by Sam Allen

Problem

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.

DateRequired filename
11/18/2008 5:04:44 PMtext-2008-11-18_05-04-44-PM.bin
11/23/2004 12:05:47 AMtext-2004-11-23_12-05-47 AM.bin

Solution: DateTime and string.Format in C#

My first attempt at putting the current date in a filename was not a great approach. I used the default ToString() on DateTime and then the Replace method. This was effective, but the readability is so poor I won't even show it here.

Example: putting the DateTime in a filename cleanly

Here we use string.Format, and combine it with DateTime.Now. This is much clearer and straightforward than using Replace. It is an example of string.Format syntax.

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");
    }
}

The important parts of the above code are what the first parameter to string.Format contains. You can see it starts with a 0 in curly brackets.

"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

Here's what Windows Vista will show the file name the above program generates in the directory. You can see it starts in "text" and ends in ".bin".

Question: can I use this with Environment.SpecialFolder?

Yes, and 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.

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);
        // C:\Users\Sam\Documents\text-2008-11-18_05-23-13-PM.bin
    }
}

Question: how can I change the format string separators?

You can simply replace 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.

Summary: programmatic file names with DateTimes

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.

Dot Net Perls
About
Sitemap
DateTime
DateTime Tips and Tricks
Pretty Date Formatting
Use DateTime for Filenames
FromOADate and Excel Dates
Get Days Elapsed From DateTime
New
GZIP Accept-Encoding Request
Convert bool to int
© 2008 Sam Allen. All rights reserved.