【发布时间】:2011-08-30 20:56:50
【问题描述】:
正如标题所示,如何获取当前操作系统驱动器,以便将其添加到字符串中,例如:
MessageBox.Show(C:\ + "My Documents");
谢谢
【问题讨论】:
正如标题所示,如何获取当前操作系统驱动器,以便将其添加到字符串中,例如:
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\ 与 @987654324 @) 并在旧版本中本地化(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 返回当前目录。
【讨论】: