<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Martijn's C# Programming Blog &#187; registry</title>
	<atom:link href="http://www.dijksterhuis.org/tag/registry/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Modifying the Windows Registry in C#</title>
		<link>http://www.dijksterhuis.org/modifying-the-windows-registry-in-c/</link>
		<comments>http://www.dijksterhuis.org/modifying-the-windows-registry-in-c/#comments</comments>
		<pubDate>Mon, 24 Nov 2008 05:19:27 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[registry]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=245</guid>
		<description><![CDATA[
One wrong move and your dead, or at least your computer. Nothing is more nerve wracking than manipulating the Windows Registry. In the following example we show how you can (safely!) create your own little part of the registry and store and retrieve your applications configuration. Which is a nice way to store user names, [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/registry.jpg" alt="" title="Modifying the Windows Registry in c#" width="500" height="300" class="alignnone size-full wp-image-259" /></p>
<p><em>One wrong move and your dead, or at least your computer. Nothing is more nerve wracking than manipulating the Windows Registry. In the following example we show how you can (safely!) create your own little part of the registry and store and retrieve your applications configuration. Which is a nice way to store user names, passwords and anything else that you fancy. </em></p>
<p><span id="more-245"></span></p>
<p>The registry is Windows central database of information on all its settings, stored there by applications, drivers and system software. If you have never worked with the registry before then start the &#8220;regedit&#8221; program on your computer &#8212; just be careful not to change anything!</p>
<p><a href="http://www.dijksterhuis.org/wp-content/uploads/2008/11/registry.gif"><img src="http://www.dijksterhuis.org/wp-content/uploads/2008/11/registry-300x242.gif" alt="" title="Using the Windows Registry in C#" width="300" height="242" class="alignnone size-medium wp-image-252" /></a></p>
<p>As you can see from the image above, the registry is a tree structure. There are nodes, and each can have sets of names/values and further sub-nodes.</p>
<p><strong>Why would you want to access the registry?</strong></p>
<ol>
<li>To look up system configuration information stored by Windows (there are thousands of these)
<li>To store your applications configuration
</ol>
<p>In this example we will only be looking at the second reason, storing your applications information. The example will shows you how to create your own sub tree. As one computer can have more than one user using it your application will typically store its settings separately for each user.</p>
<p>The registry is accessed in C# through the <em>Microsoft.Win32</em> namespace. The most important classes are:</p>
<ul>
<li>Microsoft.Win32.Registry &#8211; this class provides access to the registry
<li>Microsoft.Win32.RegistryKey &#8211; this class represents a key in the registry
</ul>
<p><strong>Creating our own keys</strong></p>
<p>We are looking to store our applications data for the current user only.  <em>Microsoft.Win32.Registry.CurrentUser</em> provides us with a <em>RegistryKey</em> to the root of the <em>CurrentUser</em> tree in the Registry. As can be seen in the above graphic, the &#8220;Software&#8221; section of <em>CurrentUser</em> is where programs store their information:</p>
<p>To create our own little section (called &#8220;ourapp&#8221;) we need to create a sub-key here:</p>
<p><small><br />
string OurAppKeyStr = @&#8221;SOFTWARE\OurApp&#8221;;<br />
RegistryKey OurAppRootKey = CurrentUserKey.CreateSubKey (OurAppKeyStr);<br />
</small></p>
<p>To keep it interesting we create the following structure:</p>
<p><small><br />
[HKEY_CURRENT_USER\software\ourapp]<br />
[HKEY_CURRENT_USER\software\ourapp\config]:X<br />
[HKEY_CURRENT_USER\software\ourapp\config]:Y<br />
[HKEY_CURRENT_USER\software\ourapp\users]:Name<br />
[HKEY_CURRENT_USER\software\ourapp\users]:Password<br />
</small></p>
<p>So below our Applications key, we need two more sub-keys: config &#038; users. These are created in the same fashion as our applications key:</p>
<p><small><br />
RegistryKey ConfigKey = OurAppRootKey.CreateSubKey(&#8221;config&#8221;);<br />
RegistryKey UsersKey = OurAppRootKey.CreateSubKey(&#8221;users&#8221;);<br />
</small></p>
<p>To add values to the registry, we simply add them to the keys we have created. The <em>SetValue()</em> function takes a name/value pair. It defaults to &#8220;String&#8221; , but for the example we are a little more explicit. The <em>RegistryValueKind</em> enum provides us with the types possible:</p>
<table>
<tr>
<td>RegistryValueKind.Binary</td>
<td>Binary data</td>
</tr>
<tr>
<td>RegistryValueKind.DWord</td>
<td>32-bit number</td>
</tr>
<tr>
<td>RegistryValueKind.QWord</td>
<td>64-bit number</td>
</tr>
<tr>
<td>RegistryValueKind.ExpandString</td>
<td>&#8220;This is a string with %PATH%&#8221; in it, the %PATH% is expanded on query</td>
</tr>
<tr>
<td>RegistryValueKind.MultiString</td>
<td>An Array of String[]</td>
</tr>
<tr>
<td>RegistryValueKind.String</td>
<td>A regular string</td>
</tr>
</table>
<p>To set a value we simple call:</p>
<p><small><br />
ConfigKey.SetValue(&#8221;X&#8221;,12,RegistryValueKind.DWord);<br />
UsersKey.SetValue(&#8221;Password&#8221;,&#8221;35a6a$&#8221;,RegistryValueKind.String);<br />
</small></p>
<p>We need to ensure that the data is writing to the registry:</p>
<p><small><br />
ConfigKey.Flush();<br />
UsersKey.Flush();<br />
</small></p>
<p>The <em>PrintTree()</em> function in the example shows how we can travel through and explore through the tree recursively. For a given key, we can query <em>GetSubKeynames</em> which returns an string array of names. Using the name a call to <em>OpenSubKey</em> returns a new <em>RegistryKey</em>. In turn we can then call <em>GetSubKeyNames</em> on that key again.</p>
<p><small><br />
foreach (string SubKeyName in Root.GetSubKeyNames())<br />
  PrintTree(Root.OpenSubKey(SubKeyName));<br />
</small></p>
<p>Because your windows registry is probably already crowded with information we will clean up at the end of the example by removing our created tree. We do not have to step through the tree and delete each sub-tree individually. Instead <em>DeleteSubKeyTree</em> removes an entire sub tree (and as  this function is quite dangerous, use it with care!)</p>
<p><small><br />
// Remove the &#8220;OurApp&#8221; subtree from the Registry<br />
CurrentUserKey.DeleteSubKeyTree(OurAppKeyStr);<br />
</small></p>
<p><strong>The Example Code</strong></p>
<pre class="brush: c#">
using System;
using Microsoft.Win32;

namespace RegistryTest
{
    class MainClass
    {

        // PrintTree
        //
        // This routine recursively steps through the registry
        // and prints each sub tree and its values

        public static void PrintTree(RegistryKey Root)
        {
            // Print the name of the current key
            Console.WriteLine(&quot;{0}&quot;,Root.Name);

            // Check if this key has any other subkeys
            // If so, travel deeper into the tree
            foreach (string SubKeyName in Root.GetSubKeyNames())
             PrintTree(Root.OpenSubKey(SubKeyName));

            // Print each of the values for this key
            foreach(string RootName in Root.GetValueNames())
                Console.WriteLine(&quot;{0}={1}&quot;,RootName,
                                            Root.GetValue(RootName) );
        }

        public static void Main(string[] args)
        {
            // Obtain a link to the current users registry entries
            RegistryKey CurrentUserKey = Microsoft.Win32.Registry.CurrentUser;
            RegistryKey OurAppRootKey = null;
            RegistryKey ConfigKey = null;
            RegistryKey UsersKey = null;

            // Create a section for our application
            // Note: The @ in front of the string ensures that the compiler ignores the slash
            string OurAppKeyStr = @&quot;SOFTWARE\OurApp&quot;;
            OurAppRootKey = CurrentUserKey.CreateSubKey (OurAppKeyStr);

            // Save the X,Y values
            ConfigKey = OurAppRootKey.CreateSubKey(&quot;config&quot;);
            ConfigKey.SetValue(&quot;X&quot;,12,RegistryValueKind.DWord);
            ConfigKey.SetValue(&quot;Y&quot;,20,RegistryValueKind.DWord);

            // Save the username , password values
            UsersKey = OurAppRootKey.CreateSubKey(&quot;users&quot;);
            UsersKey.SetValue(&quot;Name&quot;,&quot;Martijn&quot;,RegistryValueKind.String);
            UsersKey.SetValue(&quot;Password&quot;,&quot;35a6a$&quot;,RegistryValueKind.String);           

            // Flush all the changes
            ConfigKey.Flush();
            UsersKey.Flush();

            // Print a tree of our applications keys
            PrintTree(OurAppRootKey);

            // Remove the &quot;OurApp&quot; subtree from the Registry
            CurrentUserKey.DeleteSubKeyTree(OurAppKeyStr);

        }
    }
}
</pre>
<p><strong>Using the Registry with Mono</strong></p>
<p>Although Unix does not have a registry as such it is still possible to use the above code under Mono. If you are looking in the registry for Windows specific configuration values &#8212; or those stored by other Windows only applications &#8212; you will  come up empty. This registry is just a shell. It however provides a good cross-platform method of storing your own configuration values. </p>
<p>Mono will create a tree of small XML files under the users home directory. So for example, in our example we created the key &#8220;HKEY_CURRENT_USER\software\ourapp\config&#8221; which is stored in  an XML file.  This XML file  is located in the following directory:</p>
<p>~/.mono/registry/CurrentUser/software/ourapp/config</p>
<p>The values we stored are kept in a file called values.xml:</p>
<pre class="brush: xml">
&lt;values&gt;
&lt;value name=&quot;X&quot; type=&quot;int&quot;&gt;12&lt;/value&gt;
&lt;value name=&quot;Y&quot; type=&quot;int&quot;&gt;20&lt;/value&gt;
&lt;/values&gt;
</pre>
<p><small>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/fboyd/">Florian</a></small></p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/modifying-the-windows-registry-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
