Sunday, October 10, 2010

C# Tutorial: Create and Delete Registry Keys

Here is the code

Microsoft.Win32.RegistryKey key;
private void button1_Click(object sender, EventArgs e)
{
    // Create the registry key.
    // It is more secure to write data to the user folder — Microsoft.Win32.Registry.CurrentUser 
    // — rather than to the local computer — Microsoft.Win32.Registry.LocalMachine.
    key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("MyRegKey");
    key.SetValue("IsTutorial", "Yes");
    key.Close(); 
}

private void button2_Click(object sender, EventArgs e)
{
    // Delete a registry key
    Microsoft.Win32.Registry.CurrentUser.DeleteSubKey("MyRegKey"); 
}

private void Form1_Load(object sender, EventArgs e)
{
    // NOTE: Before typing this code make sure you have created the registry key
    // Otherwise you'll get an exception error !!! 
            
    // Open a registry key.
    // "true" means the key it's writable
            
    key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("MyRegKey",true);
    // An example of using the registry key
    if (key.GetValue("IsTutorial").ToString() == "Yes")
    {
        MessageBox.Show("This is a Tutorial!");
        key.SetValue("IsTutorial", "No");
    }
    else MessageBox.Show("This is Not a Tutorial!");
}

Or download the solution

1 comment:

  1. Hello Sir, This tutorial is awesome..And I want to know how to create a DWORD in CURRENT_USER\Software\Test\ ? Thanks in Advance

    ReplyDelete