Condividi tramite


Fun with Enums and 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.

 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 do "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 enums 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.

 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

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

Technorati Tags: Visual Studio .NET