无法访问注册表HKLM密钥

Sur*_*esh 3 .net c# registry

无法从Windows XP限制/访客用户帐户访问注册表HKLM密钥

public int GetEnabledStatus()
{
 RegistryKey hklm = Registry.LocalMachine;
 int Res;
 try
 {
    RegistryKey run1 = 
      hklm.OpenSubKey(@"Software\Microsoft\Windows\myApp", true);
    hkcu.OpenSubKey(@"Software\Microsoft\Windows\myApp", true);
    Res = int.Parse(run1.GetValue("enabled").ToString());
 }
 catch
 {
    Res = 0;
    return Res;
 }
 finally
 {
    hklm.Close();
 }
  return Res;
}
Run Code Online (Sandbox Code Playgroud)

此代码在管理员用户帐户中正常工作,在有限/来宾帐户下调用此函数不会返回值.有什么工作吗?

Mil*_*ian 6

您正在"写入"模式下打开键(第二个参数设置为"true").作为受限用户,您无权写入HKLM.通过将模式更改为"readonly"(第二个参数设置为"false"),您应该能够读取该值.

我建议更新代码如下:

private static int GetEnabledStatus()
{
    const int defaultStatus = 0;
    using (var key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\myApp")) // open read-only
    {
        int valueInt;
        var value = (key != null
            ? key.GetValue("enabled", defaultStatus)
            : defaultStatus);
        return (value is int
            ? (int)value
            : int.TryParse(value.ToString(), out valueInt)
                ? valueInt
                : defaultStatus);
    }
}
Run Code Online (Sandbox Code Playgroud)

不需要异常处理,在作为有限用户运行时在我的机器上运行:-).