Accesing the Registry values:
This article is primarily aimed for explaining how to access the values that are stored in System registry .it's sometimes necessary for programmers to access the registry to obtain information about the operating system or older applications or sometimes for security purposes information like database connection string etc would be stored in System registry. Registry is the base class that is used to access the Windows Registry in NET which is there in Microsoft.Win32 Namespace. I would also try to explain the registry structure before explaining how access using c#. The registry has a hierarchical structure with the base unit as registry key the corresponding class for accessing this key is RegistryKey. Here I would like to mention one point that RegistryKey class in dotnet uses some unmanaged system resources, so its use should be protected with a try/finally block that cleans up the system resources when the object is no longer being used. These keys in turn would have sub keys. Top level keys cannot be deleted by user written applications and sub keys can be modified if the permissions are there. .NET programs must have the RegistryPermission to access the registry. Registry will have five sections (top level Registry keys) which are also called sub trees named HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS, and HKEY_CURRENT_CONFIG Below class which explains how to access a key value from registry
using System; using Microsoft.Win32; namespace MyRegistryAccess { public class ClsRegistry { public ClsRegistry () { // // TODO: Add constructor logic here // } public string Getvalue() { //open the registry key present in top level key HKEY_CURRENT_USER //for opening the registry key HKEY_LOCAL_MACHINE we have to use //Registry.LocalMachine.For HKEY_USERS we have to use Registry.Users //For HKEY_CLASSES_ROOT we have to use Registry.ClassesRoot //For HKEY_CURRENT_CONFIG we have to use Registry.CurrentConfig
RegistryKey regKey = Registry.CurrentUser.OpenSubKey("\\Software\\IAI"); //Give your sub key name as shown if (regKey == null) //if the Registry key is not found it returns null //so check if this line is to check if the key //we have given is exiting or not { throw new Exception("Registry values are not found"); } else { try { string myValue = (string)regKey.GetValue("MyKey");//Vlaue of the Key in Registry return myValue; } catch(Exception ex) { throw ex; } finally { // Clean up the objects regKey.Close(); } }
}
} }
|
| Author: Amer T. 23 Mar 2008 | Member Level: Bronze Points : 0 |
For some reason the example provided reads following key on Windows Server 2003 (but not on Vista or XP) : HKEY_USERS\S-1-5-20\Software
Any ideay why? How can I access the right key (in HKEY_CURRENT_USER)?
|