Tsukasa
Tsukasa

Reputation: 6552

Check write access to registry

So i'm checking to see if I have write access to the registry with the code below

try
{
    RegistryPermission perm = new RegistryPermission(RegistryPermissionAccess.Write, networkRegistryPath);
    perm.Demand();
}
catch (Exception ex)
{
    throw new ArgumentException("Write Access Denied");
}

rk.SetValue("PnPCapabilities", powerOff[0]);
networkCards.Add(networkRegistryPath, powerOff[0]);

if perm.Demand() failed I'd assume it would throw an error but it doesn't so I then try to write a value. It then errors with Cannot write to registry.

I put the rk.SetValue in the catch as well but I don't think I should have needed to because i'm checking before hand if I have the ability to write.

Am I missing something here?

Upvotes: 0

Views: 641

Answers (1)

Hans Passant
Hans Passant

Reputation: 941465

You are confusing CAS with Windows access permissions. They are completely different. RegistryPermission verifies that the .NET program is running with sufficient trust to access the registry. This is over and beyond the basic Windows access permission that gives a user account write access to the registry key. The .NET check is useful to sandbox code that isn't trusted, the kind that you'd load as a plug-in for example.

Your check doesn't add anything to the existing checks performed by RegistryKey.SetValue(). It already checks for both create and write permission. So you might as well remove it.

Checking for sufficient Windows access permission is pretty painful. You'll find some example code in the MSDN library article for the RegistrySecurity class, none that you could just drop into a program. There's a detailed article about it here, no idea how reliable it is.

This is pretty universally dealt with by just letting Windows perform the check and dealing with the exceptional cases. By catching the SecurityException. And by pre-emptively ensuring that an exception is unlikely so it is truly exceptional. You almost certainly need to ask for UAC elevation. Covered by this answer.

Upvotes: 1

Related Questions