Using System Wide Environment Variables in .NET Application
Introduction
Environment variables are a vital scheme for both
querying and setting vital information for serious software applications. They
are one of the techniques that when you master, you will be able to perform
tasks that are totally un-accomplishable using *ANY* other technique.
Specifically, system wide environment variables are the most valuable set of
environment variables in this regard. This tutorial aims to teach you how to
overcome this limitation and how to set environment variables from a .NET
application.
What Are System Environment Variables?
Environment variables are strings that save information
about the entire environment in your system. These string values are dynamic and
they can affect the way your system will behave on. Environment variables can be
classified into two main types:
System Variables: They affect the entire system
whatever the current user is. They are defined by Windows and saved in the
registry. You need to be an administrator to be able to modify them. You usually
need to restart your computer to make these changes effective.
User Variables: They affect the current
environment of the current system user. They can be deleted, modified,
and added by any system user. They are used by Windows setup, by some programs,
and by users. Changes to these variables are saved to the registry and be
effective immediately.
Examples of Environment Variables
In the following I will give you some
examples about both the system and local environment variables.
Local Environment Variables
%USERNAME%: represents the current user name.
%USERPROFILE%: represents the location of the profile of the current
user.
%ALLUSERSPROFILE%: represents the location of the all users' profile.
%CD%: represents the current directory string.
%APPDATA%: represents the default location where applications used to
store data.
%TEMP%: represents the temporary directories that are used by the current
user applications.
System Environment Variables
%COMPUTERNAME%: represents the name of the
computer.
%OS%: represents the running operating system's name.
%PATH%: represents the search path for programs or executable files.
%HOMEPATH%: represents the full path of the user home directory.
%HOMESHARE%: represents the network path of the user shared home
directory.
%DATE%: represents the date of the current computer.
%TIME%: represents the current time.
%NUMBER_OF_PROCESSORS%: specifies the number of processors installed on
the computer.
%PROCESSOR_IDENTIFIER%: returns a description of the processor.
%PROCESSOR_LEVEL%: represents the current processor model number.
%RANDOM%: returns a random digital number between 0 and 32767.
%SYSTEMDRIVE%: represents the drive that contains the Windows root
directory.
%SYSTEMROOT%: represents the location of the Windows root directory.
%WINDIR%: represents the location of the operating system directory.
Manipulating Environment Variables
You can add new environment variable, modify or delete an
existing one using one of the following ways.
Using Windows Environment Variables Properties Dialog
Box:
You can view, add, or change an environment variable
directly from Windows as following:
-Right click my computer, and then click Properties.
-Choose the Advanced tap in the System Properties dialog box.
-Click the Environment Variables button. The Environment dialog will appear as
shown in figure1.
-Select the variable you need to modify or delete, then click the suitable
button.

Figure 1 - Environment Variables Dialog box
Using Command Prompt:
In the command prompt you can use the set command to
create, change, or delete environment variables.
To view a variable just type "Set
VariableName".
To Create a variable type "Set VariableName=Value"
To delete a variable type "Set VariableName="
Manipulating Environment Variables in .NET
The .Net framework provides the "Environment" class to
give the programmer the ability to manipulate the environment variables
programmatically and in an easy way. With this class you can retrieve
information about a given environment variable. Edit or delete an environment
variable, and create a new environment variable. You can also specify wither the
manipulation of a specific environment variable affects only the environment
variables stored in the current process, or in the Windows operating system
registry key reserve for the current user or local machine. This class comes
with a great set of properties and methods that ease your journey with
environment variables usage.
Let us take a real example to demonstrate this wonderful
class.
.Net Example
To download the complete example just clicks
here.
Open up your Visual Studio 2005 and create a new Windows
application. In Form1 design View put the following buttons as illustrated in
the following figure.

Figure 2 - Example1 User Interface design
Get Value
In the "Get Environment Variable 1" double click event
handler type the following lines of code.
'First way
MsgBox("CurrentDirectory: " + _
System.Environment.CurrentDirectory)
MsgBox("OSVersion: " + _
System.Environment.OSVersion.ToString)
MsgBox("ProcessorCount: " + _
System.Environment.ProcessorCount.ToString)
MsgBox("UserName: " + System.Environment.UserName)
MsgBox("WorkingSet: " + _
System.Environment.WorkingSet.ToString)
Dim str As String = "LogicalDrives: "
Dim LD As String()
LD = System.Environment.GetLogicalDrives
Dim i As Integer
For i = 0 To LD.Length - 1
str = str + LD(i) + " ,"
Next
MsgBox(str)
' Another way
MsgBox("Windir: " + _
System.Environment.GetEnvironmentVariable("Windir"))
MsgBox("COMPUTERNAME: " + _
System.Environment.GetEnvironmentVariable("COMPUTERNAME"))
MsgBox("Cd: " + System.Environment.GetEnvironmentVariable("Cd"))
MsgBox("Temp: " + _
System.Environment.GetEnvironmentVariable("Temp"))
As you may notice there are two ways you can choose from
to obtain the value of an environment variable. The first way is using the
direct properties of the environment class to get a specified common set of
environment variables. The other way is throw the use of the "GetEnvironmentVariable"
method, which take the variable name as input and return its value. This
method is more flexible than using the direct class properties. By using it you
can get the value of environment variables not supports by the class properties
like the variables you create.
Create New Variable
In the "Create Environment Variables" double click event
handler type the following lines of code.
System.Environment.SetEnvironmentVariable("MyVarEx1", _
"process var", EnvironmentVariableTarget.Process)
System.Environment.SetEnvironmentVariable("MyVarEx2", _
"user var", EnvironmentVariableTarget.User)
System.Environment.SetEnvironmentVariable("MyVarEx3", _
"machine var", EnvironmentVariableTarget.Machine)
MsgBox("Done")
To create a new variable you have to use the "SetEnvironmentVariable"
method passing to it the variable name and value. When the variable name does
not exist the method creates a new variable with the specified name and assigns to
it the specified value. The third input parameter to this method is the
environment variable target which is one of the following three types: process,
user, or machine.
With the Process type the environment variable
stored or retrieved from the environment block associated with the current
process, and it will be destroyed when the process is terminated.
With the User type the environment variable is
stored in the system registry under the "HKEY_CURRENT_USER\Environment" key.
When the environment variable is created it is stored in the system registry but
not in the current process. This means that if it is a setting environment
variable the current process will not be affected, but the incoming new
processes will. This kind of environment variables are not deleted by the
process termination, only the copy of the variable in the terminated process
block will be destroyed.
With the Machine type the environment variable is
stored in the system registry under the "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session
Manager\Environment" key. When the environment is created it will not be stored
in the current process environment variables block, but when any system user
creates a new process the new created environment variable will be copied to its
environment variables block. When the current process is terminated the
environment variables stored in its block will be destroyed, and the other copy
in the registry will persist until a user removes it programmatically or
by means of an operating system tool.
View Created Environment Variables
In the "Get Create Environment Variables" double click
event handler type the following lines of code.
MsgBox("MyVarEx1 (process): " + _
System.Environment.GetEnvironmentVariable( _
"MyVarEx1", EnvironmentVariableTarget.Process))
MsgBox("MyVarEx2 (user): " + _
System.Environment.GetEnvironmentVariable( _
"MyVarEx2", EnvironmentVariableTarget.User))
MsgBox("MyVarEx3 (machine): " + _
System.Environment.GetEnvironmentVariable( _
"MyVarEx3", EnvironmentVariableTarget.Machine))
Use this code to view the values of the environment
variables created in the above section. The result will be as following:

Figure 3 - Process Environment Variable

Figure 4 - User Environment Variable

Figure 5 - Machine Environment Variable
Edit an Environment Variable
In the "Edit Environment Variables" double click event
handler type the following lines of code.
System.Environment.SetEnvironmentVariable _
("MyVarEx1", "process var1", EnvironmentVariableTarget.Process)
System.Environment.SetEnvironmentVariable _
("MyVarEx2", "user var1", EnvironmentVariableTarget.User)
System.Environment.SetEnvironmentVariable _
("MyVarEx3", "machine var1", EnvironmentVariableTarget.Machine)
MsgBox("Done")
To edit an environment variable use the "SetEnvironmentVariable"
method supplying to it the variable name and the new value. When the variable
name found the operating system will change its value to the new given one.
Run the application, create the variables, view
them, edit the variables, and then view them again.
Delete an Environment Variable
In the "Delete Environment Variables" double click event
handler type the following lines of code.
System.Environment.SetEnvironmentVariable _
("MyVarEx1", Nothing, EnvironmentVariableTarget.Process)
System.Environment.SetEnvironmentVariable _
("MyVarEx2", Nothing, EnvironmentVariableTarget.User)
System.Environment.SetEnvironmentVariable _
("MyVarEx3", Nothing, EnvironmentVariableTarget.Machine)
MsgBox("Done")
To delete a specific environment variable use the "SetEnvironmentVariable"
method supplying to it the environment variable name and nothing in the value
parameter. If the variable is found it will be deleted otherwise no action will
be taken.
If you click this button in our running example and then
view the environment variables you will get nothing in the value section. This
means that the variables are deleted.
.Net Limitation
As we stated before when a new user or machine
environment variable is created or edited the current running processes are not
affected by these changes. This is a limitation in the .Net Environment class.
Sometimes you need to notify all the currently running processes with these
changes so they are aware of the new variable, and the variable becomes
system wide as intended. To do this we need to use the "SendMessageTimeOut"
Win32 API function with the window handle set to "HWND_BROADCAST" to notify all
top level windows in the system including disabled or invisible unopened
windows.
For further information
Refer to the online copy of Microsoft Developers Network at
http://msdn.microsoft.com or use your own local copy of MSDN.
|