Last active
August 29, 2015 14:10
-
-
Save mkoertgen/33f8b90050599c3c3335 to your computer and use it in GitHub Desktop.
Spike for reading environment variables from Registry in C# (avoids problems with refreshing environment values in process session chains)
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.Diagnostics; | |
using Microsoft.Win32; | |
namespace Hello.RegEnv | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Debugger.Launch(); | |
var envVar = args[0]; | |
// This does not work from your installer shell when the installer added some new environment variables | |
var expandedViaEnv = Environment.GetEnvironmentVariable(envVar); | |
// This always gets the fresh and current environment value. This works with ClickOnce, too! | |
var expandedViaReg = GetEnvVarFromRegistry(envVar); | |
Console.WriteLine("{0} => {1} (Session)", envVar, expandedViaEnv); | |
Console.WriteLine("{0} => {1} (Registry)", envVar, expandedViaReg); | |
Console.WriteLine("Press any key."); | |
Console.ReadKey(); | |
} | |
private static object GetEnvVarFromRegistry(string envVar, string defaultValue = null) | |
{ | |
var safeDefault = defaultValue ?? String.Empty; | |
var value = (String)Registry.GetValue(@"HKEY_CURRENT_USER\Environment", envVar, safeDefault); | |
if (value == safeDefault) | |
value = | |
(String)Registry.GetValue( | |
@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", envVar, safeDefault); | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment