四联光电智能照明论坛

标题: C#读取注册表的权限问题 [打印本页]

作者: gxm771208    时间: 2016-10-28 11:33
标题: C#读取注册表的权限问题
C#读取注册表非常简单方便,指定路径后,设置对应的字段和属性值即可。
但是从Windows Vista开始,读取注册表就开始需要权限了。当然可以简单的使用管理员权限打开,或者在程序的安全性中设置其打开方式为管理员都行。但是这样多少还是在客户端后的用户层面的设置。如何才能把些工作放在开放端呢。
经过研究发现有2种办法。
方法一
1、使用ClickOnce设置,这个方法网上都有就是在项目属性的安全性中选择Click Once安全选项。
2、再app.manifast中进行修改,可以在其中看到以下文字

       <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 节点。
        -->
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
……
  </security>

注册的部分已经说的非常清楚,根据需要进行修改即可。但是无论选择其他任选的2个,在编译时都会报错。其实这里再把Click Once的安全选项关闭即可,因为app.manifest文件已经存在了。

方法二
在C#的RegistryKey中就包括了安全选项的内容。

        private static void SetRegister()
        {
            string regpath = "SOFTWARE\\Q-Das\\QTrans\\UAES";
            RegistryKey uaes = Registry.LocalMachine.OpenSubKey(regpath,
                RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);
            if (uaes == null)
                uaes = Registry.LocalMachine.CreateSubKey(regpath, RegistryKeyPermissionCheck.ReadWriteSubTree);
            uaes.SetValue("Version", "1.0", RegistryValueKind.String);
            uaes.SetValue("Author", "Andrew Hao", RegistryValueKind.String);
            uaes.SetValue("LastUpdate", "2013-2-22", RegistryValueKind.String);
            uaes.SetValue("AppPath", Application.StartupPath, RegistryValueKind.String);

            object obj = uaes.GetValue("InstallDate", null);
            if (obj == null)
                uaes.SetValue("InstallDate", DateTime.Now.ToString(), RegistryValueKind.String);

            obj = uaes.GetValue("InstallDate", "Failed...");
            MessageBox.Show(obj.ToString());
        }
上面加黑部分指定了相应的权限,选择FullControl即可获得全部权限。
作者: gxm771208    时间: 2016-10-28 11:34
其中方法二如果是操作LocalMachine的话,也同样不被允许




欢迎光临 四联光电智能照明论坛 (http://5xhome.com/) Powered by Discuz! X3.2