zoukankan      html  css  js  c++  java
  • 用 C# 在 Windows 7 中写注册表想到的

    摘自: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 中都会遇到这个问题吧

  • 相关阅读:
    骑行的乐趣
    亲子运动会
    【转载】程序员接私活经验总结,来自csdn论坛语录
    【原创】Asp.Net MVC 学习笔记之使用Model验证
    【转载】经典js技巧
    【原创】关于Sqlserver的LogFiles超大的问题
    【总结】Winform编程常用小技巧
    【总结】WebBrowser相关资料索引
    【原创】Asp.Net MVC学习笔记之使用AcceptVerbs标签来制定Action的响应行为
    【转载】一个资深SOHO程序员对新人的建议网上接活(转自CSDN)
  • 原文地址:https://www.cnblogs.com/haight/p/3292720.html
Copyright © 2011-2022 走看看