Search code examples
c#castingdatetime-format

Get datetime value from registry


hi i save datetime value to registry by this code

string keyName = @"HKEY_CURRENT_USER\ITC";
string keyValue = "test";
string valueT1 = "T1";
string valueT2 = "T2";

 DateTime dateT1 = DateTime.Now;
 DateTime dateT2 = dateT1.AddDays(180);
 Registry.SetValue(keyName, valueT1, dateT1);
 Registry.SetValue(keyName, valueT2, dateT2);

but when i try to get that value again by this code

DateTime regTime1;
DateTime regTime2;
regTime1 = (DateTime) Registry.GetValue(keyName, valueT1, null);
regTime2 = (DateTime)Registry.GetValue(keyName, valueT2, null);

it's give error "Spesified cast is not valid"
any idea how to do it rightly?


Solution

  • You could probably write/read DateTime to the registry with the following methods

    These methods are storing the DateTime in the QWORD registry format (A 64-bit binary number)

    public static void SetDate(string keyName, string valueName, DateTime dateTime) 
    {
       Registry.SetValue(keyName,valueName, dateTime.ToBinary(), RegistryValueKind.QWord);
    }
    
    public static DateTime GetDate(string keyName, string valueName)
    {
       var result = (long)Registry.GetValue(keyName,valueName);
       return DateTime.FromBinary(result);
    }
    

    Note : there is no error checking here, and please do due-diligence before using them

    the registry is not the place to be playing if you are unsure