我有一个代码段,我试图在其中写入Windows注册表,以便我可以使跟踪应用程序过期。
public RegistryKey rootKey;
public RegistryKey regKey;
public long expiry;
// Use this for initialization
void Start()
{
int period = 21; // trial period
string keyName = "/Datefile.txt";
long ticks = DateTime.Today.Ticks;
rootKey = Registry.CurrentUser;
regKey = rootKey.OpenSubKey(keyName);
if (regKey == null) // first time app has been used
{
regKey = rootKey.CreateSubKey(keyName);
expiry = DateTime.Today.AddDays(period).Ticks;
regKey.SetValue("expiry", expiry, RegistryValueKind.QWord);
regKey.Close();
}
else
{
expiry = (long)regKey.GetValue("expiry");
regKey.Close();
long today = DateTime.Today.Ticks;
if (today > expiry)
{
Debug.Log("Application has expired.");
Application.Quit();
}
}
}
但这给了我这个错误
ArgumentException: Type does not match the valueKind Microsoft.Win32.Win32RegistryApi.SetValue . . .
即使我尝试在此行中设置对象,但也会产生相同的错误
regKey.SetValue("expiry", new Expiry(), RegistryValueKind.QWord);
答案 0 :(得分:0)
这仅对32位的DWord有效。
您正在尝试将long值放入32位二进制数中。这是行不通的。
您可以将long转换为unsigned int。
regKey = rootKey.CreateSubKey(keyName);
expiry = DateTime.Today.AddDays(period).Ticks;
var uintVal = (uint)expiry;
regKey.SetValue("expiry", uintVal, RegistryValueKind.DWord);
regKey.Close();
现在,当您转换回来时:
long myTicks = Convert.ToInt64(myRegValue);
编辑:
QWord在后台存储为字符串,您可以尝试直接将其存储为字符串,但是我怀疑这不是您的问题
void Start()
{
int period = 21; // trial period
string keyName = "/Datefile.txt";
long ticks = DateTime.Today.Ticks;
rootKey = Registry.CurrentUser;
regKey = rootKey.OpenSubKey(keyName);
if (regKey == null) // first time app has been used
{
regKey = rootKey.CreateSubKey(keyName);
expiry = DateTime.Today.AddDays(period).Ticks;
regKey.SetValue("expiry", expiry.ToString(), RegistryValueKind.String);
regKey.Close();
}
else
{
var s = regKey.GetValue("expiry").ToString();
expiry = long.Parse(s);
regKey.Close();
long today = DateTime.Today.Ticks;
if (today > expiry)
{
//Debug.Log("Application has expired.");
//Application.Quit();
}
}
}