如何获得当前的Windows目录例如C:\在C#

如标题所示,如何获得当前的操作系统驱动器,以便将其添加到string中,例如:

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

谢谢

添加一个系统IO参考,

 using System IO; 

然后写下你的代码

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

此代码将设置Windows已安装的本地驱动器号的path 。 你可以使用上面的变量进行更多的修改。

例如:

 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); 

如果您不介意一点解析: http : //msdn.microsoft.com/en-us/library/system.environment.systemdirectory.aspx

Environment.systemdirectory返回当前目录。