Skip to content

Instantly share code, notes, and snippets.

@gscattolin
Created September 10, 2013 18:19
Show Gist options
  • Save gscattolin/6513375 to your computer and use it in GitHub Desktop.
Save gscattolin/6513375 to your computer and use it in GitHub Desktop.
Writing/Reading Registry using C#
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