How to Find the Parent Directory in C#

How do I find the parent directory in C#?

You can use System.IO.Directory.GetParent() to retrieve the parent directory of a given directory.

Get parent directory of parent directory

DirectoryInfo d = new DirectoryInfo("\\\\networkLocation\\test\\test");
if (d.Parent.Parent != null)
{
string up2 = d.Parent.Parent.ToString();
}
else
{
string up2 = d.Root.ToString().Split(Path.DirectorySeparatorChar)[2];
}

Is what I was looking for. Apologies for any confusion caused!

How do I find the parent directory of a path?

upDir = Directory.GetParent(path).FullName;

Search parent directory from DirectoryInfo

Actually I thought there is an already existing way or function but if I have to write it myself then this solution I wrote worked for me

    private static string GetParent(string directoryPath, string parent)
{
DirectoryInfo directory = new DirectoryInfo(directoryPath);
while (directory.Parent!=null)
{
if (directory.Parent.Name.ToLower() == parent.ToLower())
{
return directory.Parent.FullName;
}

directory = directory.Parent;
}

return null;
}

C# path to certain parent directory

You can use the DirectoryInfo class to do this relatively easily with a little iterative function.

    public string GetParent(string path, string parentName)
{
var dir = new DirectoryInfo(path);

if (dir.Parent == null)
{
return null;
}

if (dir.Parent.Name == parentName)
{
return dir.Parent.FullName;
}

return this.GetParent(dir.Parent.FullName, parentName);
}

Find the parent directory in c#

I also needed such a function to find the parent directory of a folder seamlessly. So I created one myself:

        public static string ExtractFolderFromPath(string fileName, string pathSeparator, bool includeSeparatorAtEnd)
{
int pos = fileName.LastIndexOf(pathSeparator);
return fileName.Substring(0,(includeSeparatorAtEnd ? pos+1 : pos));
}

Just send pathSeparator ("\" for windows and "/" for unix-like paths).
set last parameter true if you want separator included at the end. for ex:
C:\foo\

How do I get the path to the parent directory as relative path

This gets the parent and maintains relative path info:

 Console.WriteLine(Path.GetDirectoryName(@".\bin\debug"));

Getting path to the parent folder of the solution file using C#

Try this:

string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName,"abc.txt");

// Read the file as one string.
string text = System.IO.File.ReadAllText(startupPath);


Related Topics



Leave a reply



Submit