12.9. Parsing Paths in Environment Variables
Problem
You need to parse multiple paths contained in environment variables, such as PATH or Include.
Solution
You can use the Path.PathSeparator field or the ; character to extract individual paths from an environment variable with a value that consists of multiple paths and place them in an array. Then, you can use a foreach loop to iterate over each individual path in the PATH environment variable and parse each path. This process is illustrated by the ParsePathEnvironmentVariable method:
public static void ParsePathEnvironmentVariable()
{
string originalPathEnv = Environment.GetEnvironmentVariable("PATH");
string[] paths = originalPathEnv.Split(Path.PathSeparator);
foreach (string s in paths)
{
string pathEnv = Environment.ExpandEnvironmentVariables(s);
if(!string.IsNullOrEmpty(pathEnv))
Console.WriteLine("Individual Path = " + pathEnv);
Console.WriteLine();
}
}If the PATH environment variable contains the following:
PATH=Path=C:\WINDOWS\system32;C:\WINDOWS
and 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 individually. To distinguish each individual path from the others, Microsoft Windows uses the semicolon character. (Other operating systems might use a different character; Unix, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access