C#
  Home arrow C# arrow Page 3 - Working with Windows Registry in C#
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Working with Windows Registry in C#
By: Barzan "Tony" Antal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 6
    2008-03-05

    Table of Contents:
  • Working with Windows Registry in C#
  • The Basics
  • Let's Do It!
  • More Techniques
  • Final Words

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Working with Windows Registry in C# - Let's Do It!


    (Page 3 of 5 )

    The guideline for every programming article is to do first things first. Launch  Visual Studio and create a new C# console application project. I myself am using the VS2005. As soon as this step is completed, let's begin coding. You need to add the following line at the end of the namespace declarations. We need the Microsoft.Win32 namespace.

    using Microsoft.Win32;

    Now we are allowed to use the Registry and RegistryKey classes. The first stands for just the root keys, such as HKCR, HKCU, HKLM, HKU, and HKCC. The latter represents all the subkeys of the selected root key. This is important because we can't work explicitly with the root-key, since it is read-only and also a critical part of the Windows registry. So what we do is access the rootkey and then work with its subkeys.

    RegistryKey regkey = Registry.CurrentUser;

    regkey = regkey.OpenSubKey("SoftwareTutorial");

    The above code snippet creates a new regkey object that selects the HKCU root-key. Then we proceed to use the OpenSubKey() method, which opens the explicitly specified subkey (SoftwareTutorial); notice that we use double backslashes (you can avoid the use of double backslashes if you type an @ sign prior to the argument). The method returns null if, for whatever reason, the desired subkey cannot be found.

    As always we need to do some error handling. To avoid the latter scenario, we use the following if condition:

    if (regkey == null)

    {

          Console.WriteLine("Couldn't open the desired subkey.");

          return;

    }

    At this stage, I hope that you haven't skipped a step in the previous section where we created our test subkey titled "Tutorial" in HKCUSoftware and that you have also added some values to it. If you failed to do so, then please stop for a moment and do it now. Once you are ready, we are going to continue writing another code snippet that reads and prints out all of the name-data pairs from our Tutorial subkey.

    The code attached below starts with a method called GetValueNames(). It does nothing but retrieve an array of strings that contain all the value names associated with this key. Basically, think of it like retrieving all of the names from the name-data pair. Now glance below and check out the snippet.

    string[] valnames = regkey.GetValueNames();

    int i = 0;

    foreach (string s in valnames)

    {

          string val = (string)regkey.GetValue(valnames[i++]);

          Console.WriteLine(s + " contains " + val);

    }

    As you can see we have accomplished this task using the GetValue() method. It retrieves the value that is associated with the name you desire (argument). Just for clarification, the valnames is a string that contains the name of each name-data pair that's located in our subkey. In my case, it contains DS, AF, SC, DA, DH. Using the GetValue() method, we retrieve the data that's associated with each of them.

    It is useful to get into the habit of always closing your registry object because it also flushes its contents in case it has been modified. This is a great practice and I can guarantee that being memory efficient is always an advantage. That's why we are now going to close that regkey object and then launch our console application.

    regkey.close();

    Here we are launching our registry manipulation application for the first time. In my case, I've got the following output (attached below). However, keep in mind that this depends on the name-data pairs that you've created in the specific Tutorial subkey.

    DS contains Dev Shed

    AF contains ASP Free

    SC contains SEO Chat

    DA contains Dev Articles

    DH contains Dev Hardware

    Oh, and to convince you that indeed I've got these values in my Tutorial subkey, I am attaching the following screen shot directly from Regedit:

    You might be wondering what specifies their sequence and why they have been listed that way, or more appropriately, why DS, AF, SC, DA, and DH is their order. Well, that's how I created those name-data pairs. Microsoft's very own Regedit lists them in alphabetical order.

    By now you should be able to read from the Windows registry. That's great! The next step is learning how to write to the registry. To accomplish this, we are going to use the method called CreateSubKey(), which works in exactly the same fashion as OpenSubKey(). For the purpose of this article we are going to work in the same Tutorial subkey.

    regkey = Registry.CurrentUser;

    regkey = regkey.CreateSubKey("SoftwareTutorialNewSubKey");

    Here we have created and accessed our newly created NewSubKey subkey located in HKCUSoftwareTutorial. After this step, we are going to create two new name-data pairs in NewSubKey. We do this using the SetValue() method.

    regkey.SetValue("TestValueName", "Our Value");

    regkey.SetValue("AnotherTestValue", "Second Value");

    Now if we attach the code snippet that retrieves and prints out all of the values from our subkey once again, then these two will also appear. Here's the output:

    TestValueName contains Our Value

    AnotherTestValue contains Second Value

    Finally, we have learned how to read from and write to the Windows registry. Now we need to clarify two more things: modification and deleting. That's what the next page covers. There you'll also find a few smart tricks. And we'll move on to wrap up everything that we've just learned throughout this tutorial. The entire source code is also going to be attached for you to download, if you had difficulty following the instructions.

    More C# Articles
    More By Barzan "Tony" Antal


       · Thanks for reading this tutorial. I hope you've found it informative and education....
       · Clean, crisp to the point introductory article, keep it up.Thanks
       · I'd be interested in code clips necessary to elevate the current user to a level...
     

    C# ARTICLES

    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT