views:

352

answers:

6

I know that the following should work:

Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine)

My problem with this call is that if for some reason someone decided to remove the "windir" Env Var , this won't work.

Is there an even more secure way to get the System drive?

A: 

Theres an environment variable called SystemDrive

C:\>SET SystemDrive
SystemDrive=C:
Eoin Campbell
Unfortunately, that method suffers from the same problem as the original WinDir environment variable - a user can arbitrarily change or remove it from their environment.
Greg Hewgill
+5  A: 

This one returns the path to the system directory (system32).

Environment.GetFolderPath(Environment.SpecialFolder.System)

You may be able to use that, then you don't need to rely on environment variables.

Fredrik Mörk
It's worth noting that GetFolderPath elates your environment variable fears since it uses SHGetFolderPath internally.
Richard Szalay
+2  A: 

You can use the GetWindowsDirectory API to retrieve the windows directory.

Richard Szalay
A: 
string windir = Environment.SystemDirectory; // C:\windows\system32
string windrive = Path.GetPathRoot(Environment.SystemDirectory); // C:\

Note: This property internally uses the GetSystemDirectory() Win32 API. It doesn't rely on environment variables.

Serge - appTranslator
+4  A: 

One thing i actually maybe misunderstand is that you want the System Drive, but by using "windir" you'll get the windows folder. So if you need a secure way to get the windows folder, you should use the good old API function GetWindowsDirectory.

Here is the function prepared for C# usage. ;-)

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern uint GetWindowsDirectory(StringBuilder lpBuffer, uint uSize);

    private string WindowsDirectory()
    {
        uint size = 0;
        size = GetWindowsDirectory(null, size);

        StringBuilder sb = new StringBuilder((int)size);
        GetWindowsDirectory(sb, size);

        return sb.ToString();
    }

So if you really need the drive on which windows is running, you could afterwards call

System.IO.Path.GetPathRoot(WindowsDirectory());
Oliver
Hey, that's what I said!
Richard Szalay
@Richard: That's right, but instead of just pointing to the concrete direction i added a sample, on how the function can be used.
Oliver
+1  A: 

Never read environment variables (any script or user can change them !)
The official method (MS internal, used by Explorer) is a Win32 api FAQ for decades (see Google groups, Win32, System api)