简体   繁体   中英

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?

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

Try this code:

DateTime dateTime1;
if (DateTime.TryParse((string)Registry.GetValue(keyName, valueT1, DateTime.MinValue),
    out dateTime1))
{
     ........      
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM