Created
February 6, 2023 16:56
-
-
Save TheXenocide/b5600eee7b670c146b98320fc12dfc08 to your computer and use it in GitHub Desktop.
Process Environment Variable Testing
This file contains hidden or 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
void Main() | |
{ | |
var psi = new ProcessStartInfo("cmd") | |
{ | |
UseShellExecute = false | |
}; | |
psi.Environment.OrderBy(kvp => kvp.Key).Dump("Current Process"); | |
var original = new Dictionary<string, string>(psi.Environment); | |
psi.Environment.Clear(); | |
var systemVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine).Cast<DictionaryEntry>().ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value); | |
var userVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User).Cast<DictionaryEntry>().ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value); | |
foreach (var kvp in systemVars) | |
{ | |
psi.Environment.Add(kvp.Key, kvp.Value); | |
} | |
foreach (var kvp in userVars) | |
{ | |
if (psi.Environment.TryGetValue(kvp.Key, out var existingValue)) | |
{ | |
if (kvp.Key.ToUpperInvariant() == "PATH") | |
{ | |
psi.Environment[kvp.Key] = $"{existingValue};{kvp.Value}"; | |
} | |
else | |
{ | |
psi.Environment[kvp.Key] = kvp.Value; | |
} | |
} | |
else | |
{ | |
psi.Environment.Add(kvp.Key, kvp.Value); | |
} | |
} | |
systemVars.OrderBy(kvp => kvp.Key).Dump("System"); | |
userVars.OrderBy(kvp => kvp.Key).Dump("User"); | |
psi.Environment.OrderBy(kvp => kvp.Key).Dump("Flattened"); | |
var missingKeys = original.Keys.ToHashSet(); | |
missingKeys.ExceptWith(psi.Environment.Keys); | |
missingKeys.Dump("Current Process Only?"); | |
foreach (var key in missingKeys) | |
{ | |
psi.Environment.Add(key, original[key]); | |
} | |
Process.Start(psi); | |
} | |
// Define other methods and classes here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note for anyone who stumbles on this, the Windows API I was looking for was CreateEnvironmentBlock. There is a sample here, though it would be nice if the parsing code were a little more elegant and safer with handle destruction, so perhaps I will update this later when I've written my own solution.