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

621,615

Solution 1

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.

Solution 2

System.IO.Path.GetDirectoryName(filename)

Solution 3

Path.GetDirectoryName(filename);

Solution 4

You can use System.IO.Path.GetDirectoryName(fileName), or turn the path into a FileInfo using FileInfo.Directory.

If you're doing other things with the path, the FileInfo class may have advantages.

Solution 5

You can use Path.GetDirectoryName and just pass in the filename.

MSDN Link

Share:
621,615
Even Mien
Author by

Even Mien

How many licks does it take to understand a regular expression?

Updated on October 02, 2021

Comments

  • Even Mien
    Even Mien over 2 years

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