[C#] Setting and Deleting Environment Variables Dynamically within a Running Process

目次

Overview

This article explains how to dynamically add, change, or delete environment variables that are valid only within the current process during application execution. By using the Environment.SetEnvironmentVariable method, you can inject configuration values for external libraries from your code or use them as flags to switch behaviors during test execution. By default, this does not affect system-wide environment variables, and the variables are discarded when the process terminates.

Specifications (Input/Output)

  • Input:
    • variable (string): The name of the environment variable.
    • value (string): The value to set (pass null to delete the variable).
  • Output: None (void).
  • Behavior:
    • By default, EnvironmentVariableTarget.Process is applied, affecting only the current process and any child processes started from it.
    • Setting value to an empty string ("") keeps the variable with an empty value. To delete it, you must pass null.

Basic Usage

The basic flow involves setting a variable, checking its value, and then deleting it.

string key = "TEST_MODE";

// 1. Set (Assign a value)
Environment.SetEnvironmentVariable(key, "Enabled");

// 2. Delete (Assign null)
Environment.SetEnvironmentVariable(key, null);

Full Code

This is a complete console application that defines a temporary environment variable, verifies its value, and then deletes it for cleanup.

using System;

class Program
{
    static void Main()
    {
        // The name and value of the environment variable to define
        const string EnvKey = "APP_FEATURE_FLAG";
        const string EnvValue = "BetaVersion";

        Console.WriteLine("--- 1. Checking Initial State ---");
        PrintVariable(EnvKey);

        // ---------------------------------------------------------
        // Setting the environment variable (Process Scope)
        // ---------------------------------------------------------
        Console.WriteLine($"\n--- 2. Setting Environment Variable: {EnvKey} = {EnvValue} ---");
        Environment.SetEnvironmentVariable(EnvKey, EnvValue);
        
        // Verify the set value
        PrintVariable(EnvKey);

        // ---------------------------------------------------------
        // Overwriting the environment variable
        // ---------------------------------------------------------
        Console.WriteLine("\n--- 3. Overwriting the Value ---");
        Environment.SetEnvironmentVariable(EnvKey, "StableVersion");
        PrintVariable(EnvKey);

        // ---------------------------------------------------------
        // Deleting the environment variable
        // ---------------------------------------------------------
        // Passing null as the second argument removes the variable from the environment block
        Console.WriteLine("\n--- 4. Deleting the Variable (Setting null) ---");
        Environment.SetEnvironmentVariable(EnvKey, null);
        
        // Verify after deletion
        PrintVariable(EnvKey);
    }

    // Helper method to display the state of an environment variable
    static void PrintVariable(string key)
    {
        string value = Environment.GetEnvironmentVariable(key);
        if (value == null)
        {
            Console.WriteLine($"[{key}] does not exist (null)");
        }
        else
        {
            Console.WriteLine($"[{key}] = {value}");
        }
    }
}

Execution Result Example

--- 1. Checking Initial State ---
[APP_FEATURE_FLAG] does not exist (null)

--- 2. Setting Environment Variable: APP_FEATURE_FLAG = BetaVersion ---
[APP_FEATURE_FLAG] = BetaVersion

--- 3. Overwriting the Value ---
[APP_FEATURE_FLAG] = StableVersion

--- 4. Deleting the Variable (Setting null) ---
[APP_FEATURE_FLAG] does not exist (null)

Customization Points

  • Persistent Settings (Windows Only): By specifying EnvironmentVariableTarget.User or EnvironmentVariableTarget.Machine as the third argument, you can save the variable permanently as a system or user setting. Note that writing to the Machine target requires administrative privileges.
  • Value Validation: Exceptions occur if the variable name contains an equals sign (=) or if the name is too long (32,767 characters or more). Validation is necessary if using user input as a key.

Points of Caution

  • Scope of Influence: When set without an explicit target (or with EnvironmentVariableTarget.Process), changes affect only the current process and its children. They are not reflected in other running applications or the OS system settings.
  • Deletion Method: Setting an empty string "" leaves the variable defined. To return it to an “undefined” state, you must set it to null.
  • Thread Safety: Environment variables are a global state shared across the entire process. Frequent modifications in a multi-threaded environment can cause conflicts or unexpected behavior.

Application

Scope Management Class to Limit Execution Range

This is a utility that implements IDisposable to automatically restore an environment variable to its original state (or delete it) when the using block is exited. This is useful in test code.

using System;

public class ScopedEnvironmentVariable : IDisposable
{
    private readonly string _variable;
    private readonly string _originalValue;

    public ScopedEnvironmentVariable(string variable, string value)
    {
        _variable = variable;
        // Backup the original value
        _originalValue = Environment.GetEnvironmentVariable(variable);
        // Set the new value
        Environment.SetEnvironmentVariable(variable, value);
    }

    public void Dispose()
    {
        // Restore the original value (delete if the original was null)
        Environment.SetEnvironmentVariable(_variable, _originalValue);
    }
}

// Example Usage
// using (new ScopedEnvironmentVariable("MY_API_KEY", "temp-key"))
// {
//     // The environment variable is only changed within this block
// }

Summary

Environment.SetEnvironmentVariable is particularly useful for temporary environment settings during process execution, such as modifying configurations for external libraries or controlling mocks during testing. While you must explicitly specify a target for permanent changes, using the process scope is the safest and most common approach. Ensure you pass null instead of an empty string when deleting a variable.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次