What is the most secure way to retrieve the system Drive

user88637 picture user88637 · May 26, 2009 · Viewed 10.3k times · Source

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?

Answer

Serge Wautier picture Serge Wautier · May 26, 2009
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.