Registry Access, easy question hopefully

G

Guest

I am attempting to access the following registry
HKEY_LOCAL_MACHINE\Security\Policy\PolyAdtEv using the following code. This
registry has a binary representation of the settings of the audit policies on
the remote machine. If I can read it then I can interpret it and determine
what the policies are set to. I know I have proper permissions to access
this registry. The error I am getting is that the "Object reference is not
set to an instance of the object" Please let me know what i am leaving out.
Thanks.

RegistryKey environmentKey;
string remotename;

remotename = "3dboxx-7106";

environmentKey =
RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine,remotename)
.OpenSubKey("Security").OpenSubKey("Policy").OpenSubKey("PolyAdtEv");

// Print the values.
listBox1.Items.Add("There are " + environmentKey.ValueCount.ToString() +
" values for " + environmentKey.Name.ToString() + ".");

foreach(string valueName in environmentKey.GetValueNames())
{
listBox2.Items.Add(environmentKey.GetValue(valueName).ToString());
}
environmentKey.Close();
 
D

Derrick Coetzee [MSFT]

Justin said:
The error I am getting is that the "Object reference is not
set to an instance of the object"
[ . . . ]
environmentKey =
RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine,remotename)
.OpenSubKey("Security").OpenSubKey("Policy").OpenSubKey("PolyAdtEv");

Chances are that your problem is here. OpenSubKey returns null if it fails.
Either test each result for this condition before using it or wrap a try
around this one statement and catch the NullReferenceException.
Alternatively, you can use this untested wrapper class to do the checking
for you (you can't use inheritance because RegistryKey is sealed):

class RegistryKeyNotFoundException { /* Implement me */ }

class RegistryKeyWrapper
{
RegistryKey _key;
RegistryKeyWrapper(RegistryKey key) { _key = key; }
public RegistryKeyWrapper OpenSubKey(string name)
{
RegistryKey result = _key.OpenSubKey(name);
if (result == null) throw new RegistryKeyNotFoundException();
return new RegistryKeyWrapper(result);
}
public Key { get { return _key; } }
}

Now you can rewrite your above line like this and not worry about null
checking:

environmentKey =
new RegistryKeyWrapper(
RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine,remotename))
.OpenSubKey("Security").OpenSubKey("Policy").OpenSubKey("PolyAdtEv").Key;

I hope this helps. When writing about questions like this in the future,
try reproducing the problem in a Debug build and extracting the StackTrace
property of the exception to see exactly what line it occurred on.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top