Wednesday, July 3, 2013

C#.net - Registry in C#.net

In this article i will show you how to write,read and delete Registry Entry in C#.net. As far as i know i used registry operation in project when i was worked on Visual Studio 2005. This is important Concept in C#.net.

What is Registry?
The Windows Registry, usually referred to as "the registry," is a collection of databases of configuration settings in Microsoft Windows operating systems. 

What is Use of Registry?
The Windows Registry is used to store much of the information and settings for software programs, hardware devices, user preferences, operating system configurations, and much more.


In many ways, the registry can be thought of as a kind of DNA for the Windows operating system.

The registry contains registry values, located within registry keys, all within one of several registry hives. Making changes to these values and keys using Registry Editor will change the configuration that a particular value controls.

How To Access the Registry?
The Windows Registry is accessed and configured using the Registry Editor program, a free registry editing utility included with every version of Microsoft Windows.

Registry Editor can be accessed by executing regedit from the Command Prompt or from the search or run box from the Start menu.


Registry Editor is the face of the registry, and is the way to view and make changes to the registry, but it's not the registry itself. Technically, the registry is the collective name for various database files located within the Windows installation directory.



Click on Image for better View

The Hives

To get a better understanding of the inner workings of the registry, let us see the structure of the Registry.


The Registry has a hierarchal structure, like the directories on your hard disk. Each branch is called a Key. Each key can contain other keys, as well as Values. Each value contains the actual information stored in the Registry. There are three types of values; String, Binary, and DWORD - the use of these depends upon the context. 

HKEY_CLASSES_ROOT (HKCR)
Describes file type, file extension, and OLE information.

HKEY_CURRENT_USER (HKCU)
Contains user who is currently logged into Windows and their settings.

HKEY_LOCAL_MACHINE (HKLM)
Contains computer-specific information about the hardware installed, software settings, and other information. This information is used for all users who log on to this computer and is one of the more commonly accessed areas in the Registry.

HKEY_USERS (HKU)
Contains information about all the users who log on to the computer, including both generic and user-specific information.

HKEY_CURRENT_CONFIG (HKCC)
The details about the current configuration of hardware attached to the computer.


The Registry Class
The Registry class contains members to provides access to registry keys. We can define registry keys in the following order. 

CurrentUser - Stores information about user preferences.
LocalMachine - Stores configuration information for the local machine.
ClassesRoot - Stores information about types (and classes) and their properties.
Users - Stores information about the default user configuration.
PerformanceData - Stores performance information for software components.
CurrentConfig - Stores non-user-specific hardware information.

DynData - Stores dynamic data.

For example, if you want to access HKEY_LOCAL_MACHINE key, you need to call Registry.LocalMachine member which returns a RegistryKey type.

The RegistryKey Class
The RegistryKey class contains common members to add, delete, and read registry data.

Step 1
Create a Console application and give the name as SolRegistry.

Step 2
Create a Registry Helper class to perform operation on Window Registry.This class perform following Registry Operation

  • Write the registry entry at the given path with given key and value
  • Read the registry at the given path and key and returns the generic value of the key.
  • Delete Overloading function
    • Delete the registry at the given path
    • Delete the registry at the given path and key
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;

namespace SolRegistry
{
    /// <summary>
    /// All Registry Entry store in Local Machine Type
    /// Path of Local machine - HEKY_LOCAL_MACHINE
    /// </summary>
    public static class RegistryHelper
    {
        #region Field

        private static RegistryKey RegistryKeyObj = null;
        #endregion

        #region Methods

        /// <summary>
        /// Creates a registry entry at the given path with given key and value
        /// </summary>
        /// <param name="Path">Specify the Path to Create Registry Entry</param>
        /// <param name="Key">Specify Name of the Key</param>
        /// <param name="Value">Specify Value of the Key</param>
        /// <returns>Boolean</returns>
        public static Boolean Write(String Path,String Key, Object Value)
        {
            Boolean Flag = false;
            try
            {
                // Create a New SubKey
                Registry.LocalMachine.CreateSubKey(Path);
                // Open a Sub Key for Write Value
                RegistryKeyObj = Registry.LocalMachine.OpenSubKey(Path, true);
                // Set the Spcified Key and Value
                RegistryKeyObj.SetValue(Key, Value);

                Flag = true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                Registry.LocalMachine.Dispose();
                RegistryKeyObj.Dispose();
                RegistryKeyObj = null;
            }

            return Flag;
        }

        /// <summary>
        /// Reads the registry value at the given path with the given key name
        /// </summary>
        /// <typeparam name="T">Specify the Return Type</typeparam>
        /// <param name="Path">Specify the Path for Read Value</param>
        /// <param name="Key">Specify the Key</param>
        /// <returns>T</returns>
        public static T Read<T>(String Path, String Key)
        {
            T TObj = default(T);
            try
            {
                //  Open a Sub Key for Read Value
                RegistryKeyObj = Registry.LocalMachine.OpenSubKey(Path, false);
                // Get Value by given Key
                TObj = (T)RegistryKeyObj.GetValue(Key);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                Registry.LocalMachine.Dispose();
                RegistryKeyObj.Dispose();
                RegistryKeyObj = null;
            }

            return TObj;
        }

        /// <summary>
        /// Deletes the registry entry at the given path
        /// </summary>
        /// <param name="Path">Specify the Path</param>
        /// <returns>Boolean</returns>
        public static Boolean Delete(String Path)
        {
            Boolean Flag = false;
            try
            {
                // Delete the Specified Sub Key
                Registry.LocalMachine.DeleteSubKey(Path);
                Flag = true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                Registry.LocalMachine.Dispose();
            }

            return Flag;
        }

        /// <summary>
        ///  Deletes the registry entry at the given Key
        /// </summary>
        /// <param name="Path">Specify the Path</param>
        /// <param name="Key">Specify the Key</param>
        /// <returns>Boolean</returns>
        public static Boolean Delete(String Path, String Key)
        {
            Boolean Flag = false;
            try
            {
                //  Open a Sub Key for Delete Value
                RegistryKeyObj = Registry.LocalMachine.OpenSubKey(Path, true);
                // Delete the Specified Value from this Key
                RegistryKeyObj.DeleteValue(Key);
                Flag = true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                Registry.LocalMachine.Dispose();
                RegistryKeyObj.Dispose();
                RegistryKeyObj = null;
            }

            return Flag;
        }

        #endregion
    }
}

Step 3
Now use registry helper class functionality,it is look like this 

  • Write a Registry

// Write a Registry
                // Create a new Key Under HKEY_LOCAL_MACHINE\Software as Shree
                RegistryHelper.Write(@"Software\Shree", "Key1", "Visual Studio 2012");
                RegistryHelper.Write(@"Software\Shree", "Key2", "WPF");
                RegistryHelper.Write(@"Software\Shree", "Key3", "Silverlight");
                RegistryHelper.Write(@"Software\Shree", "Key4", "Window Phone 7");
                RegistryHelper.Write(@"Software\Shree", "Key5", "Window 8 App");
                RegistryHelper.Write(@"Software\Shree", "Key6", "ASP.net");

Output

Click on Image for better View
  • Read a Registry
// Read a Registry
// Retrieve Data from at given path and Key
String Key1 = RegistryHelper.Read<String>(@"Software\Shree", "Key1");
System.Console.WriteLine("Key 1 : " + Key1);

String Key2 = RegistryHelper.Read<String>(@"Software\Shree", "Key2");
System.Console.WriteLine("Key 2 : " + Key2);

String Key3 = RegistryHelper.Read<String>(@"Software\Shree", "Key3");
System.Console.WriteLine("Key 3 : " + Key3);

String Key4 = RegistryHelper.Read<String>(@"Software\Shree", "Key4");
System.Console.WriteLine("Key 4 : " + Key4);

String Key5 = RegistryHelper.Read<String>(@"Software\Shree", "Key5");
System.Console.WriteLine("Key 5 : " + Key5);

String Key6 = RegistryHelper.Read<String>(@"Software\Shree", "Key6");
System.Console.WriteLine("Key 6 : " + Key6);



  • Delete a Value of Given key
//// Delete Value of given Key
                Boolean Flag = RegistryHelper.Delete(@"Software\Shree", "Key6");
                System.Console.WriteLine(Flag ? "Delete Successfully" : "Delete not Successfully");

Output

Click on Image for better View


  • Delete SubKey defined with Subkey Path
// Delete SubKey defined with Subkey Path
                Boolean FlagReg = RegistryHelper.Delete(@"Software\Shree");
                System.Console.WriteLine(FlagReg ? "Delete Successfully" : "Delete not Successfully");

Delete entire Subkey with associated key data. 

Full Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SolRegistry
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                // Write a Registry
                // Create a new Key Under HKEY_LOCAL_MACHINE\Software as Shree
                RegistryHelper.Write(@"Software\Shree", "Key1", "Visual Studio 2012");
                RegistryHelper.Write(@"Software\Shree", "Key2", "WPF");
                RegistryHelper.Write(@"Software\Shree", "Key3", "Silverlight");
                RegistryHelper.Write(@"Software\Shree", "Key4", "Window Phone 7");
                RegistryHelper.Write(@"Software\Shree", "Key5", "Window 8 App");
                RegistryHelper.Write(@"Software\Shree", "Key6", "ASP.net");

                // Read a Registry
                // Retrieve Data from at given path and Key
                String Key1 = RegistryHelper.Read<String>(@"Software\Shree", "Key1");
                System.Console.WriteLine("Key 1 : " + Key1);

                String Key2 = RegistryHelper.Read<String>(@"Software\Shree", "Key2");
                System.Console.WriteLine("Key 2 : " + Key2);

                String Key3 = RegistryHelper.Read<String>(@"Software\Shree", "Key3");
                System.Console.WriteLine("Key 3 : " + Key3);

                String Key4 = RegistryHelper.Read<String>(@"Software\Shree", "Key4");
                System.Console.WriteLine("Key 4 : " + Key4);

                String Key5 = RegistryHelper.Read<String>(@"Software\Shree", "Key5");
                System.Console.WriteLine("Key 5 : " + Key5);

                String Key6 = RegistryHelper.Read<String>(@"Software\Shree", "Key6");
                System.Console.WriteLine("Key 6 : " + Key6);


                //// Delete Value of given Key
                Boolean Flag = RegistryHelper.Delete(@"Software\Shree", "Key6");
                System.Console.WriteLine(Flag ? "Delete Successfully" : "Delete not Successfully");

                // Delete SubKey defined with Subkey Path
                Boolean FlagReg = RegistryHelper.Delete(@"Software\Shree");
                System.Console.WriteLine(FlagReg ? "Delete Successfully" : "Delete not Successfully");
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }

        }
        
    }
}

Run the Project.

Output

Click on Image for better View

Download
Download Source Code

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete