簡體   English   中英

如何獲取當前的windows目錄,例如C#中的C:\\

[英]How to get current windows directory e.g. C:\ in C#

正如標題所暗示的,您如何獲取當前的操作系統驅動器,因此您可以將其添加到字符串中,例如:

MessageBox.Show(C:\ + "My Documents");

謝謝

添加對 System.IO 的引用:

using System.IO;

然后在你的代碼中,寫:

string path = Path.GetPathRoot(Environment.SystemDirectory);

讓我們通過顯示一個消息框來嘗試一下。

MessageBox.Show($"Windows is installed to Drive {path}");

留言框:

在查找特定文件夾(例如我的文檔)時,不要使用硬編碼路徑。 路徑可以隨 Windows 版本( C:\\Documents and Settings\\ vs C:\\Users\\ )而變化,並在舊版本中本地化( C:\\Users\\user\\Documents\\ vs C:\\Usuarios\\user\\Documentos\\ )。 根據配置,用戶配置文件可能位於與 Windows 不同的驅動器上。 Windows 可能沒有安裝在您期望的位置(它不必在\\Windows\\ )。 可能還有其他我不知道的情況。

相反,使用 Shell API ( SHGetKnownFolderPath ) 來獲取實際路徑。 在 .NET 中,這些值很容易從Environment.GetFolderPath獲得。 如果您要查找用戶的“我的文檔”文件夾:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

特殊文件夾的完整列表

您可以使用Environment.CurrentDirectory獲取當前目錄。 Environment.SystemDirectory將為您提供系統文件夾(即:C:\\Windows\\System32)。 Path.GetPathRoot會給你路徑的根:

var rootOfCurrentPath = Path.GetPathRoot(Environment.CurrentDirectory);
var driveWhereWindowsIsInstalled = Path.GetPathRoot(Environment.SystemDirectory);

如果您不介意稍微解析一下: Environment.SystemDirectory返回當前目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM