Stopbyte

How can I get the parent folder of file in C#?

Is there a way to get the parent folder of my file using C# in wpf console program:

Example for this folder (it should work for files as well):

C:\Users\yassine\Desktop\acquisition_c\Acquisition

I need to get this:

C:\Users\yassine\Desktop\acquisition_c

thanks

You can do it like this for a File using FileInfo class:

FileInfo file_info = new FileInfo("c://Folder/FilePath.txt");
string parent_directory_path = file_info.DirectoryName;

Or you can return the Directory structure instead of simple path string like this:

FileInfo file_info = new FileInfo("c://Folder/FilePath.txt");
DirectoryInfo parent_directory = file_info.Directory;

Remember that you will need to add a reference to System.IO in your class:

using System.IO

Why not use the System.IO.Path class?!

Use Path.GetDirectoryName() method to get the given path parent directory.

The good thing about this method instead of the one @jms suggested, is it doesn’t construct any large objects (e.g. FileInfo) but instead it directly gets the exact path.

you can use Path.GetDirectoryName() Like this:

string parent_directory_path, second_parent_dir_path;

// Get our file's parent directory
parent_directory_path = Path.GetDirectoryName(@"C:\\MyDirectory\Second Directory\File.txt");

// Get the directory's own parent directory
second_parent_dir_path = Path.GetDirectoryName(parent_directory_path);

When executing that program you will get this output:

// parent_directory_path ==> "C:\\MyDirectory\Second Directory"
// second_parent_dir_path ==> "C:\\MyDirectory"
1 Like

I personally prefer the approach @isoftech suggested, Since it doesn’t require much CPU/Memory resources thus it’s best for performance.

but another even a better approach would be:

Why don’t you Parse Path string on your own?!

Something like this would do:

string my_file_path = @"C:\\MyDir\MyFiles\MyFile.txt";

/* So to get the parent directory we can simply implement this method */
public string get_parent_dir_path(string path)
{
     // notice that i used two separators windows style "\\" and linux "/" (for bad formed paths)
    // We make sure to remove extra unneeded characters.
     int index = path.Trim('/', '\\').LastIndexOfAny(new char[]{'\\', '/'});
     
    // now if index is >= 0 that means we have at least one parent directory, otherwise the given path is the root most.
    if (index >= 0)
         return path.Remove(index);
    else
        return "";
}

Doing:

get_parent_dir_path(my_file_path);

should return : "C:\\MyDir\MyFiles"

Note: We can also trim given & returned paths to avoid bad formatted paths.