设置注册表项不起作用。有时
我想在我的C#代码中设置一个注册表项,但它不会一直工作。有时它确实起作用,有时它不起作用。我开始变得疯狂...... 在以前的项目中,我没有任何问题可以写入和阅读注册表,但我现在就可以做到。设置注册表项不起作用。有时
下面是我使用的代码:
string newVersion = "10A";
RegistryKey key = null;
try
{
key = Registry.CurrentUser.CreateSubKey("Software\\stuff1\\stuff2 " + newVersion + "\\" + newVersion + "\\stuff3\\Settings", RegistryKeyPermissionCheck.ReadWriteSubTree);
key.SetValue("CopyConvertDone", "1", RegistryValueKind.String);
key.Flush();
rep.Message("CopyConvertDone registry key set for revision: " + newVersion);
}
catch (Exception e)
{
rep.Error(e);
}
finally
{
if (key != null)
{
key.Close();
}
else
{
rep.Error("Registry key is set to null.");
}
}
我已经尝试过,但没有工作: - 而不是使用CreateSubKey我试图OpenSubKey设置为true写参数。 - 增加了.Flush()方法。 - 在进行我的程序(需要此注册表项)之前,让Thread.Pause(2000)给了它一段时间(它需要此注册表项)
我没有收到任何错误并且子项已存在,但值(CopyConvertDone)doesn “T。
任何人都可以看到这个代码中的问题,并有一个可能的解决方案?
看起来正确。也许尝试删除Flush。来自MSDN:An application should only call Flush if it must be absolute certain that registry changes are recorded to disk. In general, Flush rarely, if ever, need be used.
您已经在finally语句中关闭RegistryKey。
刚刚发生了类似的事情,并使用安东尼建议的进程监视器,我发现Windows 7将我的写入重定向到HKCU\Software\Classes\VirtualStore\MACHINE
下的一个密钥。
只是一个指针,以防其他人有这个问题。
看到这个SO回答为解释为什么:http://*.com/a/10941367/155167 – Mario 2015-12-16 19:33:08
你能否澄清当它失败时会发生什么 - 你是否得到某种异常或只是在注册表中没有改变? – glenatron 2010-02-26 14:35:50
上面的代码实际上被调用了吗? – 2010-02-26 14:36:22