Sunday, September 7, 2008

Playing with Windows Registry, CRUD

In this article I’ll show the sample for each operation of CRUD for Win32 Registry. There is nothing theoretical that you should know before this, just should have idea what is win32 registry and how a developer can use it for a product.
Registry keeps information in a hierarchy format. You can put here data for using globally for a client PC. That means if you set a registry value you may use it for any number of product installed on this PC. But this place is not for storing huge data or operation data for your application, rather this place to keep information like settings information, license information, last instance value of your product, or even you can save URL for use external services. I can show hundreds of examples in where you can use Registry as a repository, but I think it’s up to you that how you would like take the advantage of this. Just leave it here and start play with this.

Create a Registry:
In Registry you will be able to save several data type but all will be under a key. In hierarchy it shows like a directory but registry will count this as a Key. So, you can add a key, string, binary, multi-string value and few more type of data under a Key. Here is the code:

string sPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\TestingRegistry\\ZAQ\\";
string sKeyName = "Address";

static void CreateSubKey(string sPath, string sKeyName, string sValue)
RegistryKey reg = null;
if (sPath.Contains("HKEY_LOCAL_MACHINE"))
reg = Registry.LocalMachine.CreateSubKey(sPath.Replace("HKEY_LOCAL_MACHINE\\", ""));
reg.SetValue(sKeyName, sValue);
else if (sPath.Contains("HKEY_CURRENT_USER"))
reg = Registry.CurrentUser.CreateSubKey(sPath.Replace("HKEY_CURRENT_USER\\", ""));
reg.SetValue(sKeyName, sValue);

Let’s consider you will call this function with this way.
So, this function will add a string value named “Phone” under the key of “ZAQ”. But if you will look at this hierarchy then you will find it will be more logical if there will be a Key name “Address” and the phone number data will be kept under this. To do this you just need to change the “sPath” and make it more extended.

string sPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\TestingRegistry\\ZAQ\\Address";

So now this one will create a Key name Address and then the Phone number will be kept.

No comments: