How do I get the directory from a file's full path?


Question

What is the simplest way to get the directory that a file is in? I'm using this to set a working directory.

string filename = @"C:\MyDirectory\MyFile.bat";

In this example, I should get "C:\MyDirectory".

1
484
2/6/2014 4:25:38 PM

Accepted Answer

If you've definitely got an absolute path, use Path.GetDirectoryName(path).

If you might only get a relative name, use new FileInfo(path).Directory.FullName.

Note that Path and FileInfo are both found in the namespace System.IO.

774
10/31/2015 11:46:37 PM

System.IO.Path.GetDirectoryName(filename)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon