Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Fun with Enums and a Generic File Date/Time Stamper

2.78/5 (6 votes)
4 Aug 2009CPOL 15.5K  
A generic file date/time stamper.

Time for a break from SQL stuff for a little .NET. Have you ever wanted to use the integer value of an enum instead of the actual enum value? For example, here is an enum I created to map datetime formats:

C#
public enum FileDatePrecision
{
    Day = 0, Hour = 2, Minute = 4, Second = 6,  
    Secondsf1 = 7, Secondsf2 = 8, Secondsf3 = 9, 
    Secondsf4 = 10, Secondsf5 = 11, Secondsf6 = 12, 
    Secondsf7 = 13
}

Never mind the weird names for the fractional second parts, was going to use millisecond, microsecond, etc., but couldn't figure out the names for all of the fractional precisions. Each "N" value for f is the fractional precision - i.e., f1 means 1/10 of a second, f2 means 1/100, and so on.

So, why did I create the enum with non-contiguous integer values? The reason is to accommodate a simple way to generate the format mask. Here's the code that returns the date time stamp with a couple of overload methods to provide defaults. It's pretty simple, just use the enum value as the substring length in order to include the characters in the format mask needed to achieve the desired output precision.

C#
public static string BuildFileDateTimeStamp(DateTime dt, FileDatePrecision precision)
{
    // Convert the enum to it's integer representation
    int precisonSequence = (int)Enum.Parse(typeof(FileDatePrecision), 
                                           precision.ToString());
    string formattedTime = "";
    if (precisonSequence > 0)
    {
        // Format the time based on the level of precision specified in the enum
        formattedTime = "_" + dt.ToString("HHmmssfffffff").Substring(0,precisonSequence);
    }
    //to get the date
    string formattedDate = dt.ToString("yyyyMMdd");
    return formattedDate + formattedTime;
}

public static string BuildFileDateTimeStamp(DateTime dt)
{
    return BuildFileDateTimeStamp(dt, FileDatePrecision.Minute);
}

public static string BuildFileDateTimeStamp()
{
    return BuildFileDateTimeStamp(DateTime.Now);
}

So, to create a filename, for example, for "StockDownloader_20090803.LOG" for use in a trace writer, I can just do:

C#
TextWriterTraceListener myWriter = new
      TextWriterTraceListener(
      System.IO.File.CreateText("StockDownloader_" 
      + Common.Utility.BuildFileDateTimeStamp() + ".log"));
      Trace.Listeners.Add(myWriter);

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)