2009-05-26 60 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)

相關問題