Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

11.16. 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 whose value 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(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...");
        }
        Console.WriteLine( );
    }
}

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:

Path = C:\WINDOWS\system32 GetDirectoryName = C:\WINDOWS GetExtension = GetFileName = system32 GetFileNameWithoutExtension = system32 GetFullPath = C:\WINDOWS\system32 GetPathRoot = C:\ HasExtension = False IsPathRooted = True Path = C:\WINDOWS GetDirectoryName ...
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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata