17.2 Retrieve the Value of an Environment Variable


Problem

You need to retrieve the value of an environment variable for use in your application.

Solution

Use the GetEnvironmentVariable , GetEnvironmentVariables , and ExpandEnvironmentVariables methods of the Environment class.

Discussion

The GetEnvironmentVariable method allows you to retrieve a string containing the value of a single named environment variable, whereas the GetEnvironmentVariables method returns an IDictionary containing the names and values of all environment variables as strings. The ExpandEnvironmentVariables method provides a simple mechanism for substituting the value of an environment variable into a string by including the variable name enclosed in percent signs (%) within the string. Here is an example that demonstrates the use of all three methods.

 using System; using System.Collections; public class VariableExample {     public static void Main () {         // Retrieve a named environment variable.         Console.WriteLine("Path = " +              Environment.GetEnvironmentVariable("Path"));         Console.WriteLine();         // Substitute the value of named environment variables.         Console.WriteLine(Environment.ExpandEnvironmentVariables(                 "The Path on %computername% is %Path%"));         Console.WriteLine();         // Retrieve all environment variables and display the values         // of all that begin with the letter 'P'.         IDictionary vars = Environment.GetEnvironmentVariables();         foreach (string s in vars.Keys) {             if (s.ToUpper().StartsWith("P")) {                 Console.WriteLine(s + " = " + vars[s]);             }         }         Console.WriteLine();         // Wait to continue.         Console.WriteLine("Main method complete. Press Enter.");         Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net