Badhri Ravikumar
Badhri Ravikumar

Reputation: 69

Find the parent directory in c#

If path = "\ProgramFiles\MobileApp\es-gl\a.dll". I want to get "\ProgramFiles\MobileApp\es-gl" alone. Just want to know the parent directory of the file a.dll. Is there Any inbuilt method in c#? I am using .net Compact Framework

Upvotes: 0

Views: 8079

Answers (6)

Gerald Versluis
Gerald Versluis

Reputation: 34013

I'm not sure but I think the FileInfo and DirectoryInfo classes are supported on the Compact Framework.

Try this:

FileInfo myFile = new FileInfo("\ProgramFiles\MobileApp\es-gl\a.dll");
string parentDirectory = myFile.Directory.Name;

According to the MSDN documentation you could also do this:

FileInfo myFile = new FileInfo("\ProgramFiles\MobileApp\es-gl\a.dll");
string parentDirectory = myFile.DirectoryName;

Check out these MSDN links for more info:

http://msdn.microsoft.com/en-us/library/system.io.fileinfo_members(v=vs.71)

http://msdn.microsoft.com/en-us/library/system.io.fileinfo.directory(v=vs.71)

Upvotes: 3

Prahlad Yeri
Prahlad Yeri

Reputation: 3653

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\

Upvotes: 3

Jonas W
Jonas W

Reputation: 3250

There is a Parent directory on FileInfo(System.IO namespace). Example code :

var file = new FileInfo(@"\ProgramFiles\MobileApp\es-gl\a.dll");
var parent = file.Directory.Parent;

Upvotes: 2

mdm
mdm

Reputation: 12630

var directory = Path.GetDirectoryName(@"c:\some\path\to\a\file.txt");
// returns "c:\some\path\to\a"

MSDN

Upvotes: 0

Dragon Creature
Dragon Creature

Reputation: 1995

You can just use the methods of the string class.

        string path = @"\ProgramFiles\MobileApp\es-gl\a.dll";
        string newPath = path.Substring(0, path.LastIndexOf('\\'));

Upvotes: 0

Jason Williams
Jason Williams

Reputation: 57902

System.IO.Path.GetDirectoryName(path)

Upvotes: 7

Related Questions