Retrieves all Environment Variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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