Created
September 10, 2013 18:19
-
-
Save gscattolin/6513375 to your computer and use it in GitHub Desktop.
Writing/Reading Registry using C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Win32; | |
... | |
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey | |
("SOFTWARE\\Test\\Preferences"); | |
if (masterKey == null) | |
{ | |
Console.WriteLine ("Null Masterkey!"); | |
} | |
else | |
{ | |
try | |
{ | |
masterKey.SetValue ("MyKey", "MyValue"); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine (ex.Message); | |
} | |
finally | |
{ | |
masterKey.Close(); | |
} | |
} | |
public string Read(string KeyName) | |
{ | |
// Opening the registry key | |
RegistryKey rk = baseRegistryKey ; | |
// Open a subKey as read-only | |
RegistryKey sk1 = rk.OpenSubKey(subKey); | |
// If the RegistrySubKey doesn't exist -> (null) | |
if ( sk1 == null ) | |
{ | |
return null; | |
} | |
else | |
{ | |
try | |
{ | |
// If the RegistryKey exists I get its value or null is returned. | |
return (string)sk1.GetValue(KeyName.ToUpper()); | |
} | |
catch (Exception e) | |
{ | |
ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper()); | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment