我在使用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选项,我得到异常:“不允许所请求的注册表访问。”
我受困严重,无法继续。
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注册表。没问题...
Windows注册表基本上是结构化的文件系统,并且具有键和值的权限。
您没有在...\MyServices\
或更深的密钥上正确设置权限-您无权从未特权的进程访问那些权限。
任一: