private unsafe static char[] GetEnvironmentCharArray()
{
// 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).
char* pStrings = Interop.Kernel32.GetEnvironmentStringsW();
if (pStrings == null)
{
throw new OutOfMemoryException();
}
try
{
// Search for terminating \0\0 (two unicode \0's).
char* p = pStrings;
while (!(*p == '\0' && *(p + 1) == '\0')) p++;
var block = new char[(int)(p - pStrings + 1)];
Marshal.Copy((IntPtr)pStrings, block, 0, block.Length);
return block;
}
finally
{
Interop.Kernel32.FreeEnvironmentStringsW(pStrings); // ignore any cleanup error
}
}