2012-02-17 66 views
1

我在使用C#编程方式读取注册表值时遇到问题。 我看了很多网站,并帮助,但找不到任何有用的。 我能够在eleveated模式下运行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选项,我得到异常:“请求的注册表访问是不允许的。”

我非常卡住,无法继续。请帮助

+0

尝试使用'regedit'导航到有问题的注册表项;右键单击该键并选择_Permissions_选项。 – LiquidPony 2012-02-17 16:31:21

+0

忘了提及,我早些时候尝试过! – Murthy 2012-02-17 16:35:11

+0

奇怪的是,我发现创作者所有者没有完全控制或读取权限,但系统,管理员和用户拥有完全控制和读取权限。创作者所有者只有特殊的权限。所以点击高级...在权限选项卡中,我看到创作者所有者,该权限仅适用于子项,但对于其他人,该权限适用于此项和子项!这让我感到惊喜! – Murthy 2012-02-17 16:40:48

回答

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注册表。没问题...

+0

它碰到的那一刻OpenSubkey,我得到例外! – Murthy 2012-02-17 16:36:40

+0

试试这种方式'Registry.CurrentUser。OpenSubKey(“Software \\ YourKey”,true);' – Alex 2012-02-20 09:50:34

+0

你们有点偏离目标 - 问题不在于通常访问注册表 - 两种方法都可以正常工作 - 问题在于注册表是只是一个文件系统,并像其他文件系统一样,限制对某些部分的访问。 – antiduh 2013-12-28 16:42:10

1

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

您没有在...\MyServices\或更深的键上正确设置权限 - 您没有权限访问您的非特权进程中的权限。

或者:

  1. 这些密钥应该被任何人读取,所以你应该更改权限,使其可读的每个人。或者 -
  2. 这些键被有意地限制在一个很好的理由,所以他们不应该是每个人都可读,在这种情况下,你的程序应该始终运行提升。