
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Parsing Paths in Environment Variables
|
717
public static void ParsePathEnvironmentVariable( )
{
string originalPathEnv = Environment.GetEnvironmentVariable("PATH");
string[] paths = originalPathEnv.Split(new char[1] {Path.PathSeparator});
foreach (string s in paths)
{
string pathEnv = Environment.ExpandEnvironmentVariables(s);
Console.WriteLine("Path = " + pathEnv);
if(pathEnv.Length > 0)
{
Console.WriteLine("Individual Path = " + pathEnv);
}
else
{
Console.WriteLine("Skipping blank environment path details " +
" as it causes exceptions...");
}
}
}
If the PATH environment variable contains the following:
PATH=Path=C:\WINDOWS\system32;C:\WINDOWS
then the output of the ParsePathEnvironmentVariable method is as follows:
Individual Path = C:\WINDOWS\system32
Individual Path = C:\WINDOWS
Discussion
When working with environment variables in particular, there are a number of cases
in which several paths may be concatenated and you need to parse each one individ-
ually. To distinguish each individual path from the others, Microsoft Windows uses
the semicolon character. (Other operating systems might use a different character;
Unix, Linux, and Mac OS X use a colon.) To make sure that we always use the cor-
rect path-separation character, the
Path class contains a public static field called