Question

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?

Was it helpful?

Solution

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());

OTHER TIPS

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.

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.

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

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)

Theres an environment variable called SystemDrive

C:\>SET SystemDrive
SystemDrive=C:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top