以编程方式访问注册表的问题

问题描述 投票:1回答:2

我在使用C#编程读取注册表值时遇到问题。我调查了许多站点并提供了帮助,但找不到任何帮助。在精简模式下运行VS时,我能够访问和读取注册表,但是在不提升模式下运行VS时,会遇到问题。最初,我从下面的代码开始

byte[] val = (byte[])Registry.GetValue("HKEY_LOCAL_MACHINE\\Software\\MyServices\\Identity\\ASPNET_SETREG", "ValueName", 0);

此选项在提升模式下工作正常,但在非提升模式下失败。将属性放在函数顶部

[RegistryPermissionAttribute(SecurityAction.Demand,Unrestricted=true)]

这没有帮助。然后尝试

[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.AllFlags)] 

仍然没有用。现在,我尝试了以下代码...

RegistryKey key = Registry.LocalMachine;            


        RegistrySecurity rs = new RegistrySecurity();
        rs = key.GetAccessControl();
        string user = "DomainName\\Username";
        rs.AddAccessRule(new RegistryAccessRule(user,
        RegistryRights.ReadKey,
        InheritanceFlags.None,
        PropagationFlags.None,
        AccessControlType.Allow));


        key.SetAccessControl(rs);//Exception: "Attempted to perform an unauthorized operation."}
        //RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG");
        //RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", false);
        //RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", RegistryKeyPermissionCheck.ReadSubTree);
        RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadPermissions);

评论SetAccessControl并使用任何OpenSubkey选项,我得到异常:“不允许所请求的注册表访问。”

我受困严重,无法继续。

c# registry
2个回答
1
投票
private RegistryKey keyR = Registry.CurrentUser.OpenSubKey("Software\\YourKey",true);
private RegistryKey keyW = Registry.CurrentUser.CreateSubKey("Software\\YourKey");

public string version
{
    get { return keyR.GetValue("VERSION", "", RegistryValueOptions.DoNotExpandEnvironmentNames).ToString(); }
    set { keyW.SetValue("VERSION", value, RegistryValueKind.String); }
}

我正在以这种方式使用Windows注册表。没问题...


1
投票

Windows注册表基本上是结构化的文件系统,并且具有键和值的权限。

您没有在...\MyServices\或更深的密钥上正确设置权限-您无权从未特权的进程访问那些权限。

任一:

  1. 这些密钥应该对任何人都可读,因此您应该更改权限以使每个人都可读。或-
  2. 这些键被有意地限制是有充分的理由,因此每个人都不应读取它们,在这种情况下,您的程序应始终运行提升权限。
© www.soinside.com 2019 - 2024. All rights reserved.