Skip to content

Instantly share code, notes, and snippets.

@michel-pi
Created April 24, 2020 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save michel-pi/af478c482404b1ae45ab275a238582ca to your computer and use it in GitHub Desktop.
Save michel-pi/af478c482404b1ae45ab275a238582ca to your computer and use it in GitHub Desktop.
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