-
Notifications
You must be signed in to change notification settings - Fork 0
/
Windoze.cs
101 lines (93 loc) · 2.63 KB
/
Windoze.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//------------------------------------------------------------------------------
//
// System.Private.Windows.cs
//
// Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
//
// Author: Jim Richardson, develop@wtfo-guru.com
// Created: Tuesday, August 21, 2001
//
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System
{
public sealed class PlatformSpecific
{
/// <summary>
/// Gets the standard new line value
/// </summary>
public static string NewLine
{
get
{
return "\r\n";
}
}
// TODO: verify the "W" versions are available on 95/98/ME
// or whatever other windoze platforms we'll target
[ DllImport("kernel32", EntryPoint="GetEnvironmentStringsW") ]
private extern static IntPtr getEnvironStrings();
[ DllImport("kernel32", EntryPoint="FreeEnvironmentStringsW") ]
private extern static int freeEnvironStrings(IntPtr p);
public static string getEnvironment()
{
IntPtr pEnv = getEnvironStrings();
int start = 0;
int offset = 0;
int length = 0;
int consecutive_nulls = 0;
int null_count = 0;
char ch;
string strEnv = null;
try
{
// the first string is just the process identifer, etc.
// the array of strings ends with double (perhaps) triple null
// if we read too far before we reach the end an exception will
// surely be thrown
while(length == 0)
{
ch = (char)System.Runtime.InteropServices.Marshal.ReadInt16(pEnv, offset);
offset += 2;
if(ch == '\0')
{
null_count++;
consecutive_nulls++;
if(start == 0 && null_count > 1)
{ // we skip the first two windows strings
// because they aren't environment variables
start = offset;
}
if(consecutive_nulls > 1)
{ // TODO: verify this length is exactly correct
// this was a quickie calculation that worked
length = offset - (consecutive_nulls + start);
}
}
else
{
consecutive_nulls = 0;
}
}
char[] arEnv = new char[length];
int index;
for(offset = start, index = 0; index < length; offset += 2, index++)
{
ch = (char)System.Runtime.InteropServices.Marshal.ReadInt16(pEnv, offset);
arEnv[index] = ch == '\0' ? '\n' : ch;
}
strEnv = new string(arEnv);
//Console.WriteLine(str);
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
strEnv = null;
}
freeEnvironStrings(pEnv);
return strEnv;
}
}
}