Search code examples
c#directory.net-cf-3.5

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


Solution

  • 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\