Sunday, August 1, 2010

How to read Windows Registry

Sometime we are required to read windows registry values in our applications. It is quite simple just 3-4 lines of code make you life easy while reading from registry.

Here we go.

I am sure you know how to Add Registry Data, lets take an example here.

Step1: Add a new Registry data, for that I will add connection string settings to my windows registry.

/*Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication\DAL]

"ConnectionString"="Persist Security Info=False;User ID=UserId;Initial Catalog=MyDatabase; Password=Password;Data Source=MyServer"*/

This will add a Registry value of “String Value” to my Registry.

Step2: Step 2 includes how you read the value of the registry by passing the key name.

Here first of all we need to include the name space

using Microsoft.Win32

Here is the function that return the value:

public string GetConnectionString()

{

RegistryKey connkey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MyApplication\DAL");

if (connkey != null)

{

object keyvalue = connkey.GetValue("ConnectionString");

return keyvalue.ToString();

}

throw new Exception("ConnectionString Connection string is not set in Windows Registry");

}

This way you get the connection string value set in the registry. I hope you got the way it needs to be achieved.

Thanks and please share your valuable comments.

No comments:

Post a Comment