简体   繁体   English

设置注册表项不起作用。 有时

[英]Setting registry key doesn't work. Sometimes

I'm trying to set a registry key in my C# code, but it doesn't work all the time. 我正在尝试在我的C#代码中设置一个注册表项,但是它并非一直都有效。 Sometimes it does work, sometimes it doesn't. 有时确实有效,有时却无效。 I'm starting to get crazy... In previous projects I had no problems writing and reading to the registry, but I do now. 我开始发疯了……在以前的项目中,写入和读取注册表没有问题,但是现在我做了。

Here's the code I'm using: 这是我正在使用的代码:

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.");
    }
}

What I already tried but didn't work: - Instead of using CreateSubKey I tried OpenSubKey with the write-parameter set to true. 我已经尝试过但无法使用的方法:-我没有使用CreateSubKey,而是尝试了OpenSubKey,并将write-parameter设置为true。 - Added the .Flush() method. -添加了.Flush()方法。 - Did a Thread.Pause(2000) to give it some time before progressing my program (which needs this registry key) -在执行我的程序之前需要Thread.Pause(2000)给它一些时间(需要此注册表项)

I don't get any error and the subkey already exists, but the value (CopyConvertDone) doesn't. 我没有收到任何错误,并且子键已经存在,但是值(CopyConvertDone)不存在。

Can anyone see a problem in this code and has a possible solution? 谁能在此代码中看到问题并找到可能的解决方案?

该代码对我来说似乎还不错,但是,如果某些时候它可以正常工作,则可以使用Process Monitor查看正在对注册表进行哪些调用以及成功/失败的情况。

Had something similar happen to me just now, and using Process Monitor as suggested by Antony I discovered Windows 7 was redirecting my writes to a key under HKCU\\Software\\Classes\\VirtualStore\\MACHINE . 刚才发生了类似的事情,并且使用了Antony建议的Process Monitor,我发现Windows 7将我的写入重定向到HKCU\\Software\\Classes\\VirtualStore\\MACHINE下的某个键。

Just a pointer in case anybody else has this issue. 只是一个指针,以防其他人遇到此问题。

Looks correct. 看起来正确。 Maybe try to remove Flush. 也许尝试删除冲洗。 From 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. 从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. 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.

Your already closing the RegistryKey in the finally statement. 您已经在finally语句中关闭了RegistryKey。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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