GetWindowsDirectory in C#

  • Thread starter Thread starter Miro
  • Start date Start date
M

Miro

Hi!

I am able to get the Windows directory by using:


[DllImport("kernel32", SetLastError=true)]
static extern unsafe uint GetWindowsDirectory(byte*
lpBuffer,uint uSize);
....
byte[] buff = new byte[512];
unsafe
{
fixed(byte *pbuff=buff)GetWindowsDirectory(pbuff,512);
}
ASCIIEncoding ae = new ASCIIEncoding();
WinDir = ae.GetString(buff);


but then I can't do anything with it. I can't even add a
String to it:

String temp = WinDir + "\\File";

Why?

/Miro
 
I am able to get the Windows directory by using:

use
System.Environment.SystemDirectory
 
Wiktor Zychla said:
use
System.Environment.SystemDirectory

Doesn't this just get the System folder, i.e. "C:\WINNT\System32" as apposed
to "C:\WINNT"?

Some alternatives are:

Path.GetDirectoryName(Environment.SystemDirectory);
Environment.ExpandEnvironmentVariables("%windir%");

The first one assumes that the system directory is always an immediate
subdirectory of the windows directory (it works because there is no trailing
"\" in the result from Environment.SystemDirectory). I'm not sure if this is
always guaranteed to be the case, but it seems like a reasonable assumption.

If you really want to go the p/invoke route, then you should use a
StringBuilder rather than unsafe code:

[DllImport("kernel32", SetLastError=true)]
public static extern uint GetWindowsDirectory(StringBuilder buffer, uint
length);

public string WindowsDirectory
{

get
{
StringBuilder buffer = new StringBuilder(260);
GetWindowsDirectory(buffer, 260);
return buffer.ToString();
}

}

HTH.
 
Back
Top