Monday, July 14, 2008

Environmental Variables

I am kinda new to C# development, as I have only been doing it for about 3-4 months at this time. I have been programming for about 3 years, 2 of which where while I was in school. My main focus is on Web Development, but recently I have been put in a position that deals with a great amount of windows development.

Anyways, that all aside, I was asked to create a program that would install a huge amount of applications, I think I am up to 45 now... and there are still more. Some of the apps that I am installing are BizTalk 2004, CRM 3.0, all of the VS apps, and so on.

I ran into a problem while installing several of my apps, they were not getting their values updated in the Path Environmental Variable. So I needed a way to do this in C#, and thought, why not just use the Win32 class. So here is what I have come up with:


try
{
RegistryKey _rKey;
object _kPath;

_rKey =
Registry.LocalMachine.OpenSubKey(@"path to Variable");
_kPath = _rKey.GetValue("Path");

_rKey.SetValue("Path", @"String Variable Here");
}
catch (Exception ex)
{
"Handle your Exceptions here"
}

I always wrap my code in Try\Catch statements, but that is just me. Also, make sure that you add the using statment to your app:

using Microsoft.Win32;

After that you declare your variables, you need both a RegistryKey variable and an object variable. We will get the Environmental Variable using the Regkey, and will get\set the value of the key with the object:

RegistryKey _rKey;
object _kPath;

set key equal to the subkey that contains your variable:

_rKey = Registry.LocalMachine.OpenSubKey(@"path to Variable");

to modify the Path Value you would use:
Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Session Manager\Environment");

Next set your object equal to the regkey variable value that you need:

_kPath = _rKey.GetValue("Path");

Notice that this is where we actually point to the Path Value of the System Environmental variable. GetValue, does just that, gets the current value of the key. You have to get the value before you can set it. Otherwise you will not know what to set.

After that you simply set the value data that you want to use:

_rKey.SetValue("Path", @"String Variable Here");

This is where you need to copy the current values of the variable, and then append your new path variables to the end.


That's it. It is pretty easy to use, and gets the job done. I am sure there are other ways to do this, but for 5 lines of code... this is the quickest way I have seen yet.

Thanks,
Chuck

No comments: