Find the parent directory in c#
-
25-06-2021 - |
Вопрос
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
Решение
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\
Другие советы
System.IO.Path.GetDirectoryName(path)
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;
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)
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('\\'));
var directory = Path.GetDirectoryName(@"c:\some\path\to\a\file.txt");
// returns "c:\some\path\to\a"