我正在编写一个调整实用程序,修改了 HKEY_CLASSES_ROOT
下的一些键。
在 Windows XP 等系统下一切正常。但在 Windows 7 下出现错误 Requested registry access is not allowed
。我猜 Vista 和 2008 也会出现这个问题。
我应该如何修改我的代码以添加 UAC 支持?
app.manifest
应该像这样:
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
</asmv1:assembly>
在Vista及其更新版本的Windows中,如果您没有管理员权限,则无法写入HKCR(或HKLM)注册表项。因此,在运行实用程序之前,您需要以管理员身份登录,为其提供需要管理员级别的清单(这将提示用户输入管理员登录信息),或者停止更改非管理员应该玩耍的地方。 :-)
如果您不需要对整个应用程序进行管理员特权,或者只需要进行一些不经常的更改,则可以在新进程中进行更改,并使用以下方式启动它:
Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";
这将以管理员身份运行进程,以执行您需要的所有注册表操作,但在完成后以正常特权返回您的应用程序。这样,它就不会每次启动时提示用户打开UAC对话框。
我尝试使用verb = "runas"
,但在尝试更新注册表值时仍然遇到了UnauthorizedAccessException。结果发现是因为没有将可写设置为true而未打开子键。
Registry.OpenSubKey("KeyName", true);
这个问题与授予应用程序运行的用户帐户必要的授权有关。如需阅读类似情况和详细响应的正确解决方案,可以访问此帖子:http://rambletech.wordpress.com/2011/10/17/requested-registry-access-is-not-allowed/
你可以像abatishchev一样做,但不需要UAC。
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
App.manifest
添加到 VS 项目的根目录,它将自动复制到输出目录作为<appname>.exe.manifest
或嵌入程序集中。 - abatishchev