用 C# 在 Windows 7 中写注册表想到的

时间:2022-06-06 21:38:20

摘自:http://blog.163.com/dpj_001/blog/static/2742941520110251500753/

某日做一个项目,需要在注册表中加入键,同时写值,操作系统环境为 Windows 7

于是写了如下代码:

try
{
RegistryKey r = Registry.LocalMachine.OpenSubKey("software",true);
} catch(Exception e){}

竟然抛出 System.Security.SecurityException Message="不允许所请求的注册表访问权。" 的异常,嘿,怪了,以前怎么没有?

想想莫非是 UAC 的问题?

于是想到两个办法

1、添加 应用程序清单文件,在其中加入

<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC 清单选项
如果希望更改 Windows 用户帐户控制级别,请用以下节点之一替换
requestedExecutionLevel 节点。 <requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" /> 如果您希望利用文件和注册表虚拟化提供
向后兼容性,请删除 requestedExecutionLevel 节点。
-->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>

2、修改代码,如下:

System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal( identity );
if(principal.IsInRole( System.Security.Principal.WindowsBuiltInRole.Administrator ))
{
// 修改注册表
}
else
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; // 获取当前可执行文件的路径及文件名
//以下 Args 为启动本程序的对应的参数
startInfo.Arguments = String.Join( " ", Args );
startInfo.Verb = "runas";
System.Diagnostics.Process.Start( startInfo );
}

哈哈,修改成功,当运行程序时提示您 是否以管理员身份运行,点击“是”,OK。

想想,恩,可能在 Vista 或 Windows 2008 中都会遇到这个问题吧