简体   繁体   中英

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

As the title suggests, how can you get the current OS drive, so you could add it in a string eg:

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

Thanks

Add a reference to System.IO:

using System.IO;

Then in your code, write:

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

Let's try it out by showing a message box.

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

留言框:

When looking for a specific folder (such as My Documents), do not use a hard-coded path. Paths can change from version-to-version of Windows ( C:\\Documents and Settings\\ vs C:\\Users\\ ) and were localized in older versions ( C:\\Users\\user\\Documents\\ vs C:\\Usuarios\\user\\Documentos\\ ). Depending on configuration, user profiles could be on a different drive than Windows. Windows might not be installed where you expect it (it doesn't have to be in \\Windows\\ ). There's probably other cases I'm not aware of.

Instead, use the Shell API ( SHGetKnownFolderPath ) to get the actual path. In .NET, these values are easily obtained from Environment.GetFolderPath . If you're looking for the user's My Documents folder:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

Full list of special folders

You can use Environment.CurrentDirectory to get the current directory. Environment.SystemDirectory will give you the system folder (ie: C:\\Windows\\System32). Path.GetPathRoot will give you the root of the path:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM