Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Retrieves all Environment Variables
using System;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.InteropServices;
namespace System
{
public static class EnvironmentEx
{
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeEnvironmentStringsA(IntPtr buffer);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetEnvironmentStringsA();
private static readonly Lazy<List<string>> _lazyEnvironmentVariables = new Lazy<List<string>>(
() =>
{
var result = new List<string>();
var buffer = GetEnvironmentStringsA();
var originalBuffer = buffer;
while (true)
{
var text = Marshal.PtrToStringAnsi(buffer);
if (string.IsNullOrEmpty(text)) break;
result.Add(text);
buffer += (text.Length + 1);
}
FreeEnvironmentStringsA(originalBuffer);
return result;
}, LazyThreadSafetyMode.ExecutionAndPublication);
public static IEnumerable<string> EnvironmentVariables
{
get
{
foreach (var value in _lazyEnvironmentVariables.Value)
yield return value;
}
}
public static string[] GetEnvironmentVariables()
{
var variables = _lazyEnvironmentVariables.Value;
var result = new string[variables.Count];
for (int i = 0; i < variables.Count; i++)
{
result[i] = variables[i];
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.