I have a piece of code like this
try
{
RegistryKey regKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\xxxx\\yyyyy");
// more code
}
catch
{
}
I don’t like the use of the empty catch block. But, it’s useful because if the user don’t have permissions to access the Registry, nothing should be done.
This piece of code gets called many times and, apart of a bad practice, I think it has poor performance.
I’ve been looking for a way to check the registry permissions before trying to access it, but the only way I’ve found to do it it’s checking for a exception with
RegistryPermission.Demand()
and check for a exception. So, that gives me no advantage with the initial approach.
¿Is there a way to check for the Registry access permissions without artificially throwing or having to check for exceptions?
Edit:
Well, looks like the .NET preferred way of doing this is trying to access the resource and check for exceptions. The article Yannick pointed shows how complex it is to deal with the Windows security model, looking for the desired access manually.
So, what I’m going to do is redesign this code a little so it only checks once for the access (catching the exception) and keeps that information, instead of constantly throwing exceptions.
This has the drawback that if the user changes the security settings “on the fly”, the code will keep denying access to the Registry. However, this is preferred if there isn’t a simple and clean way of checking for access.
Since you are creating a new key, shouldn’t you just check the parent’s permissions once?
Edit: I am unsure if there are managed ways, but you could try CheckAccess() in Stdprov.dll: http://msdn.microsoft.com/en-us/library/aa384911%28VS.85%29.aspx
Edit2: Have you tried http://msdn.microsoft.com/en-us/library/1w66447a.aspx ?
Edit3:
http://www.codeproject.com/KB/system/accessctrl3.aspx