Environment.ExpandEnvironmentVariables(String) Method

Definition

Replaces the name of each environment variable embedded in the specified string with the string equivalent of the value of the variable, then returns the resulting string.

C#
public static string ExpandEnvironmentVariables(string name);

Parameters

name
String

A string containing the names of zero or more environment variables. Each environment variable is quoted with the percent sign character (%).

Returns

A string with each environment variable replaced by its value.

Exceptions

name is null.

Examples

The following example shows how to obtain the system drive and system root variables.

C#
// Sample for the Environment.ExpandEnvironmentVariables method
using System;

class Sample
{
    public static void Main()
    {
        // Keep this information secure!
        string query = "My system drive is %SystemDrive% and my system root is %SystemRoot%";

        string str = Environment.ExpandEnvironmentVariables(query);

        Console.WriteLine(str);
    }
}
/*
This example prints:

My system drive is C: and my system root is C:\WINDOWS
*/

Remarks

COM interop is used to retrieve the environment variables from the operating system. If the environment variables cannot be retrieved due to a COM error, the HRESULT that explains the cause of the failure is used to generate one of several possible exceptions; that is, the exception depends on the HRESULT. For more information about how the HRESULT is processed, see the Remarks section of the Marshal.ThrowExceptionForHR method.

Replacement only occurs for environment variables that are set. For example, suppose name is "MyENV = %MyENV%". If the environment variable, MyENV, is set to 42, this method returns "MyENV = 42". If MyENV is not set, no change occurs; this method returns "MyENV = %MyENV%".

The size of the return value is limited to 32K.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0