Code that accesses the registry by using the Microsoft.Win32.Registry class must be granted the RegistryPermission by code access security policy. This permission type can be used to constrain registry access to specific keys and sub keys, and can also control code's ability to read, write, or create registry keys and named values.
To constrain code to reading data from specific registry keys, you can use the RegistryPermissionAttribute together with SecurityAction.PermitOnly . The following attribute ensures that the code can only read from the YourApp key (and subkeys) beneath HKEY_LOCAL_MACHINE\SOFTWARE.
[RegistryPermissionAttribute(SecurityAction.PermitOnly, Read=@"HKEY_LOCAL_MACHINE\SOFTWARE\YourApp")] public static string GetConfigurationData( string key, string namedValue ) { return (string)Registry. LocalMachine. OpenSubKey(key). GetValue(namedValue); }
To document the permission requirements of your code, and to ensure your assembly cannot load if it is granted insufficient registry access from code access security policy, add an assembly level RegistryPermissionAttribute with SecurityAction.RequestMinimum as shown in the following example.
[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum, Read=@"HKEY_LOCAL_MACHINE\SOFTWARE\YourApp")]