Click here to Skip to main content
Click here to Skip to main content

Registry handling with .NET

By , 21 May 2002
 

Introduction

Well, apparently the registry seems to have lost some of its importance with the arrival of .NET, at least that's the impression I seem to get. But luckily for us, Microsoft has given us two nice classes for doing just about anything we want to do with the registry. The classes are Microsoft.Win32.RegistryKey and Microsoft.Win32.Registry. They have both been put into the Microsoft.Win32 namespace as you can see because the registry is totally Microsoft Win32 specific. Without too much fuss, let's get into business and try and do some of the stuff we normally do with the registry.

Reading the registry

//The Registry class provides us with the 
// registry root keys
RegistryKey rkey = Registry.LocalMachine;

//Now let's open one of the sub keys
RegistryKey rkey1=rkey.OpenSubKey(
    "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");

//Now using GetValue(...) we read in various values 
//from the opened key
listBox1.Items.Add("RegisteredOwner :- " + 
    rkey1.GetValue("RegisteredOwner"));			
listBox1.Items.Add("RegisteredOrganization :- " +
    rkey1.GetValue("RegisteredOrganization"));
listBox1.Items.Add("ProductName :- " + 
    rkey1.GetValue("ProductName"));
listBox1.Items.Add("CSDVersion :- " + 
    rkey1.GetValue("CSDVersion"));
listBox1.Items.Add("SystemRoot :- " + 
    rkey1.GetValue("SystemRoot"));
    
rkey1.Close();

Writing to the registry

rkey = Registry.CurrentUser;
//The second parameter tells it to open the key as writable
rkey1 = rkey.OpenSubKey("Software",true);

// Now we create our sub key [assuming you have enough 
// rights to edit this area of the registry]
RegistryKey rkey2 = rkey1.CreateSubKey("Tweety");

//Setting the various values is done using SetValue()
//I couldn't figure out how to set the value type yet :-(
rkey2.SetValue("Name","Tweety");
rkey2.SetValue("Age",24);
rkey2.Close();
rkey1.Close();

If you open regedit, you'll see that the new key has been added and the values have indeed been written correctly.

Enumeration

Okay, we've read from and written into the registry. Now let's enumerate some values.

rkey1 = rkey.OpenSubKey("Software\\Microsoft\\" +  
    "Internet Account Manager\\Accounts\\00000001");
    
string[] s_arr = rkey1.GetValueNames();

foreach(String s in s_arr)
{
	listBox1.Items.Add(s + " :- " + rkey1.GetValue(s));
}

rkey1.Close();

Well, that's about it I guess. This was originally written as part of an internal tutorial. I didn't modify it too much except for taking better screenshots.

Thanks.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

About the Author

Nish Sivakumar
United States United States
Member
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralVery Goodmemberkulanthaivelu.v10 Nov '06 - 18:55 
Keep it up
It is very useful to me.
thanking you
 
Kulanthaivelu.V

Generalset/get default valuesussAnonymous1 Sep '02 - 18:39 
use Nothing in Visual Basic, or the empty string ("") to set/get default value.
 
the RegistryKey is simple, but so weak. not support query key. any one else wanna write a advanced lib for the reg key operations?
GeneralThank You Nish!memberMazdak16 Apr '02 - 7:48 
Your articles always have very good tips for beginners. Smile | :)
 
<html>Mazy</html>
 
"The path you tread is narrow and the drop is shear and very high,
The ravens all are watching from a vantage point near by,
Apprehension creeping like a choo-train uo your spine,
Will the tightrope reach the end;will the final cuplet rhyme?"Cymbaline-Pink Floyd


GeneralRe: Thank You Nish!memberNish [BusterBoy]16 Apr '02 - 12:16 
Thanks Mazy Smile | :)
 
Nish
 

The rumours that I am an AI bot are absolutely false. These rumours have been propogated by *them* to focus all the attention on to me, while *their* bots take over the planet. Thank y%%%% Divide by zero. Cannot proceed. Abort(y/y)?
GeneralGreat ArticlememberNick Parker22 Mar '02 - 16:30 
Nish,
Another great article, tell me though where do you find the time? Smile | :)
 
Nick Parker

GeneralRe: Great ArticlememberNish [BusterBoy]22 Mar '02 - 16:36 
Hi Nick
 
I am trying to spend more time on articles rather than on posting. That way I get to learn new stuff and finally land up that cool job in Seattle that I've always dreamed about, getting 120K annually Wink | ;-)
 
Nish
 
Yeah that's me down below Wink | ;-)
 

     

     

     

     

     

     


GeneralRegarding .NET and registry!memberNish [BusterBoy]22 Mar '02 - 14:05 
I'd like to know from more knowledgable people than me, which prolly means most of you, whether users are advised to use the registry in .NET or are they supposed to use those newly introduced .config files?
 
I mean the registry is alright for a while, but after a while it gets polluted huh?
 
Regards
Nish
 
One Nish is trouble enough.
Imagine 16 of me, dancing wild...
:jig::jig::jig::jig:
:jig::jig::jig::jig:
:jig::jig::jig::jig:
:jig::jig::jig::jig:

GeneralRe: Regarding .NET and registry!memberAndy Smith22 Mar '02 - 19:24 
It's suggested that the registry be avoided by application developers.
 
for application specific items, use the application .config.
 
For user specific storage, or even just storage with a little more privacy, use System.IO.IsolatedStorage.
GeneralRe: Regarding .NET and registry!memberNish [BusterBoy]22 Mar '02 - 20:50 
Thanks Andy.
I guess for new apps, people should avoid the registry.
But when porting legacy apps, I guess people might still need registry access.
 
Nish
 
Yeah that's me down below Wink | ;-)
 

     

     

     

     

     

     


GeneralRe: Regarding .NET and registry!memberJason Hooper23 Mar '02 - 5:29 
It would absolutely make my day if the use of .conf files became standard on the Windows platform Smile | :)
 
- Jason
(SonorkID 100.611)
 
Veni, vidi, VC
      - I came, I saw, Visual C
GeneralRe: Regarding .NET and registry!memberJames T. Johnson23 Mar '02 - 19:02 
The .NET provided application configuration files are read once at execution then its no longer accessed. It is also read-only so you can't store something that could change for the application in them.
 
This leaves you to your own devices, however there are a few function calls to make it easier to properly place this type of stuff.
 
System.Environment.GetFolderPath() returns the path of the "special" folder you wish to retreive. To get the directory best suited for a system-wide application settings file pass in System.Environment.SpecialFolder.CommonApplicationData. To get the best directory for user settings pass in System.Environment.SpecialFolder.ApplicationData for roaming users or System.Environment.SpecialFolder.LocalApplicationData for non-roaming users.
 
Some have suggesting putting your settings into a DataSet, then using the Read/WriteXml methods to persist the data. But -- as always -- you are free to come up with your own solutions Smile | :)
 
James
 
Sonork ID: 100.11138 - Hasaki
"Smile your little smile, take some tea with me awhile.
And every day we'll turn another page.
Behind our glass we'll sit and look at our ever-open book,
One brown mouse sitting in a cage."
"One Brown Mouse" from Heavy Horses, Jethro Tull 1978

GeneralRe: Regarding .NET and registry!memberJames T. Johnson25 Mar '02 - 14:48 
You learn something new everyday. Rather than using the GetFolderPath you can refer to the Application class (in the System.Windows.Forms namespace).
 
Here are some nice static properties to use Smile | :)
 
Application.
  • CommonAppDataPath - Gets the path for the application data that is shared among all users.
  • CommonAppDataRegistry - Gets the registry key for the application data that is shared among all users.
  • LocalUserAppDataPath - Gets the path for the application data of a local, non-roaming user.
  • UserAppDataPath - Gets the path for the application data of a roaming user.
  • UserAppDataRegistry - Gets the registry key of the application data specific to the roaming user.
James
 
Sonork ID: 100.11138 - Hasaki
"Smile your little smile, take some tea with me awhile.
And every day we'll turn another page.
Behind our glass we'll sit and look at our ever-open book,
One brown mouse sitting in a cage."
"One Brown Mouse" from Heavy Horses, Jethro Tull 1978

GeneralRe: Regarding .NET and registry!memberRama Krishna25 Mar '02 - 15:27 
These paths return very weird values and are version dependent. I was excited about them but I had to give it up.
GeneralRe: Regarding .NET and registry!memberCareBear28 May '02 - 22:28 
I see some of the others here advice against the use of registry, but there are certain things you can do easier and faster with the registry, and that's stuff like user-specific values and other stuff like application load at startup, and you have a whole area of different settings and tweaks you can do (just be carefull not to mess up anything) and be sure to know where you save anything, as you should remove it when the user uninstalls the application (you could maybe even include a "clean-up" app to remove the values) ... but I see absolutely no harm in the use of Win32 Registry for storing configurations and settings. In my current project we use both Application.Config and the registry to make the application "customized" to the different users, if there are any on the local machine. We use the Application Data folder to store stuff like cached datasets and so forth.
 
With Windows XP the registry also got a few little upgrades to make it faster, and from our experience there is nothing that can compare to it Wink | ;)
 
Follow the common rules and guidelines for Windows registry and you'll do just fine Laugh | :laugh:
 

/Sondre Bjellås
GeneralRe: Regarding .NET and registry!memberNish - Native CPian29 May '02 - 0:46 
Thanks for the info Smile | :)
 
Nish
 

Regards,
Nish
Native CPian.
Born and brought up on CP.
With the CP blood in him.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 22 May 2002
Article Copyright 2002 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid