How to get the parent directory in C#?

We can use the DirectoryInfo class to get a parent of a specified folder or directory in C#. You must import the System.IO before you can use this class.

using System.IO;

The Parent property of DirectoryInfo returns the parent directory as a DirectoryInfo. We can use the FullName property to get the full name of the directory. 

The following code snippet does the same.

string root = @"C:\Temp\Mahesh";
DirectoryInfo di = new DirectoryInfo(root);
Console.WriteLine(di.Parent.FullName);

Download the free book:>Working with Directories in C#


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.