private static IDictionary GetEnvironmentVariablesCore()
{
// Format for GetEnvironmentStrings is:
// (=HiddenVar=value\0 | Variable=value\0)* \0
// See the description of Environment Blocks in MSDN's
// CreateProcess page (null-terminated array of null-terminated strings).
// Note the =HiddenVar's aren't always at the beginning.
// Copy strings out, parsing into pairs and inserting into the table.
// The first few environment variable entries start with an '='.
// The current working directory of every drive (except for those drives
// you haven't cd'ed into in your DOS window) are stored in the
// environment block (as =C:=pwd) and the program's exit code is
// as well (=ExitCode=00000000).
var results = new LowLevelDictionary<string, string>();
char[] block = GetEnvironmentCharArray();
for (int i = 0; i < block.Length; i++)
{
int startKey = i;
// Skip to key. On some old OS, the environment block can be corrupted.
// Some will not have '=', so we need to check for '\0'.
while (block[i] != '=' && block[i] != '\0') i++;
if (block[i] == '\0') continue;
// Skip over environment variables starting with '='
if (i - startKey == 0)
{
while (block[i] != 0) i++;
continue;
}
string key = new string(block, startKey, i - startKey);
i++; // skip over '='
int startValue = i;
while (block[i] != 0) i++; // Read to end of this entry
string value = new string(block, startValue, i - startValue); // skip over 0 handled by for loop's i++
results[key] = value;
}
return results;
}