我正在尝试在我的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,而是尝试使用write-parameter设置为true的OpenSubKey。 - 添加了.Flush()方法。 - Thread.Pause(2000)在推进我的程序(需要这个注册表项)之前给它一些时间吗?
我没有收到任何错误,并且该子项已经存在,但值(CopyConvertDone)没有。
任何人都可以在此代码中看到问题,并且有可能的解决方案吗?
答案 0 :(得分:3)
代码看起来不错,但是如果它在某些时候工作,那么可能使用Process Monitor来查看对注册表的调用以及成功/失败的内容。
答案 1 :(得分:2)
刚才有类似事情发生在我身上,并且按照Antony的建议使用Process Monitor我发现Windows 7将我的写入重定向到HKCU\Software\Classes\VirtualStore\MACHINE
下的密钥。
只是一个指针,以防其他任何人遇到此问题。
答案 2 :(得分:0)
看起来正确。也许尝试删除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。