2009-05-26 106 views
11

我知道下面应该工作最稳妥的办法:什么是检索系统驱动器

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

我与此调用的问题是,如果由于某种原因,有人决定删除“WINDIR”的环境变量,这是行不通的。

是否有更安全的方式获取系统驱动器?

回答

4

我其实可能误解的一件事是你想要系统驱动器,但通过使用“windir”你会得到windows文件夹。因此,如果您需要安全方式来获取windows文件夹,则应该使用良好的旧API函数GetWindowsDirectory。

这是为C#使用准备的函数。 ;-)

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

所以,如果你真的需要的Windows运行的驱动器,你可以事后调用

System.IO.Path.GetPathRoot(WindowsDirectory()); 
+0

嘿,那就是我说的! – 2009-06-08 10:03:29

0

即使世界称为SystemDrive

C:\>SET SystemDrive 
SystemDrive=C: 
+0

不幸的是,该方法存在与原始WinD相同的问题ir环境变量 - 用户可以任意更改或从其环境中删除它。 – 2009-05-26 10:56:35

8

这一个返回路径到系统目录(SYSTEM32)的环境变量。

Environment.GetFolderPath(Environment.SpecialFolder.System) 

您也许可以使用它,那么您不需要依赖环境变量。

+0

值得注意的是,由于GetFolderPath在内部使用了SHGetFolderPath,所以它引发了你的环境变量的担忧。 – 2009-05-26 10:44:05

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

注意:此属性在内部使用GetSystemDirectory()Win32 API。它不依赖于环境变量。

1

从来不看环境变量(任何脚本或用户可以改变它们!)
官方方法(微软内部,资源管理器使用)是几十年来的Win32 api常见问题解答(请参阅Google groups,Win32,System api)