13

I need some guidance in reading/writing/saving the values in Registry.I am new to this concept of saving things in registry

I have a Winform where i have to read/write to a App.config file and change the username and password using a winform.In my winform i have 2 textboxes and when i enter values and hit submit it changes the values in app.config.I somehow did that and no issues.

Now I need to send what ever values I have entered in the Textboxes to registry and save them thr and I should also be able to read them.

How shoud I do that ?

demonplus
  • 5,613
  • 12
  • 49
  • 68
user1410658
  • 551
  • 3
  • 10
  • 20
  • Plenty of info about this on Google, [heres something to start with](http://www.codeproject.com/Articles/3389/Read-write-and-delete-from-registry-with-C) – musefan May 22 '12 at 16:11
  • Can't you make some simple google search ? –  May 22 '12 at 16:18

2 Answers2

34

using Microsoft.Win32;

To write:

Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyProgram", "Username", "User1");

To read:

string username = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyProgram",
                                    "Username", "NULL").ToString();

In read where I have put NULL - thats the value to return if the value you are looking for isn't there.

So if you did:

if(username == "NULL")
{
    // it doesn't exist, handle situation here
}

Hope this helps.

marbel82
  • 925
  • 1
  • 18
  • 39
Bali C
  • 30,582
  • 35
  • 123
  • 152
  • Yes Buddy.Thank you.... Do you have any Example to display here about this registry read/write/save ?? – user1410658 May 22 '12 at 16:18
  • @user1410658 No probs. Updated question with actual data. If you had a key named `MyProgram` and you set the value `Username` with the first code and you get the value using the second. Once you make the change you don't need to save it. – Bali C May 22 '12 at 16:28
  • @user1410658 No problem, if this answers your question you should accept it, just click the tick :D – Bali C May 23 '12 at 08:11
  • Just to note: The route may translate to: `HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MyProgram`. – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ Aug 30 '17 at 09:29
15

Here is a quick code:

private void button1_Click(object sender, EventArgs e)
{
    Microsoft.Win32.RegistryKey exampleRegistryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("ExampleTest");
    exampleRegistryKey.SetValue("Name", textBox1.Text);
    exampleRegistryKey.Close();
}

Now if you run regedit and must see under HKEY_CURRENT_USER\ExampleTest

demonplus
  • 5,613
  • 12
  • 49
  • 68
HatSoft
  • 11,077
  • 3
  • 28
  • 43