28

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

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

Thanks

Miles
  • 283
  • 1
  • 3
  • 4
  • 1
    possible duplicate of [How to get the name of the drive that the OS is installed on?](http://stackoverflow.com/questions/200066/how-to-get-the-name-of-the-drive-that-the-os-is-installed-on) – Teoman Soygul Aug 30 '11 at 21:00

4 Answers4

70

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

Message box:

Community
  • 1
  • 1
Otávio Décio
  • 73,752
  • 17
  • 161
  • 228
16

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

Mofi
  • 46,139
  • 17
  • 80
  • 143
josh3736
  • 139,160
  • 33
  • 216
  • 263
6

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);
Mofi
  • 46,139
  • 17
  • 80
  • 143
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

If you don't mind a little parsing: Environment.SystemDirectory returns the current directory.

Mofi
  • 46,139
  • 17
  • 80
  • 143
N_A
  • 19,799
  • 4
  • 52
  • 98