views:

192

answers:

2

couldn't access registry HKLM keys from windows xp limited/guest user accounts

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;
}

this code works fine in administrator user accounts, under limited/guest accounts call to this function doest not return value. is there any work around

+1  A: 

If you only want to read the key, use the overload of OpenSubKey which takes only a string.

Henrik
+4  A: 

You are opening the keys in "write" mode (2nd parameter is set to 'true'). As a limited user, you do not have permissions to write to HKLM. By changing mode to "readonly" (2nd parameter set to 'false') you should be able to read the value.

I would recommend updating the code as follows:

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);
    }
}

No need for exception handling, works on my machine when run as limited user :-).

Milan Gardian
yes correct, i changed now it works
JKS