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

Even Mien picture Even Mien · Mar 23, 2009 · Viewed 561.1k times · Source

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".

Answer

Jon Skeet picture Jon Skeet · Mar 23, 2009

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.