当我要更新值时,拒绝访问注册表项

Pay*_*ali 10 c# registry

我想编辑名为"usbstor"值的注册表项,这是我在更新方法中的代码

  try
        {
            string path = baseRegistryKey + "\\" + SubKey;
            Registry.SetValue(path, KeyName, KeyValue, RegistryValueKind.DWord);

            return true;
        }
        catch (Exception e)
        {
            // AAAAAAAAAAARGH, an error!
            ShowErrorMessage(e, "Writing registry " + KeyName.ToUpper());
            return false;
        }
Run Code Online (Sandbox Code Playgroud)

和path ="HKEY_LOCAL_MACHINE\system\currentControlset\services\usbstor"keyname ="start"当我运行代码时,我将获得"访问注册表项'HKEY_LOCAL_MACHINE\system\currentControlset\services\usbstor'被拒绝"是什么万阿英,蒋达清?

mwi*_*ski 15

可执行文件

HKEY_LOCAL_MACHINE在注册表中始终是受保护的空间,因此您需要至少获得特权Power User或运行您的可执行文件As Administrator(从您的解决方案构建的应用程序,应该在./bin文件夹中)或禁用UAC.无论哪种方式,只要您没有配置/设置任何方式,它将在Visual Studio中很麻烦.

请注意,如果您尝试使用Run.. -> regeditUAC也会提示您,这样不仅限制了您的应用,还限制了注册表本身的访问权限.

在Visual Studio中

在打开之前提升Visual Studio Run as administrator足以从代码编辑注册表.

申请清单

为了将来的使用,您可能希望创建app.manifest并将应用程序设置为始终需要管理员权限.右键单击您的项目Solution Explorer,然后:Add -> New Item... -> Application Manifest File.在新创建的应用程序清单中,更改行:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />
Run Code Online (Sandbox Code Playgroud)

到线

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Run Code Online (Sandbox Code Playgroud)

从现在开始,如果不以管理员身份运行,它将始终提示UAC.如果您Visual Studio以非管理员身份运行,它将尝试以管理员身份重新启动IDE,并在继续之前提示执行此操作.