您可以使用下面的靜態方法來計算給定一個相對父路徑:
public static string GetRelativeParentPath(string basePath, string path)
{
return GetRelativePath(basePath, Path.GetDirectoryName(path));
}
public static string GetRelativePath(string basePath, string path)
{
// normalize paths
basePath = Path.GetFullPath(basePath);
path = Path.GetFullPath(path);
// same path case
if (basePath == path)
return string.Empty;
// path is not contained in basePath case
if (!path.StartsWith(basePath))
return string.Empty;
// extract relative path
if (basePath[basePath.Length - 1] != Path.DirectorySeparatorChar)
{
basePath += Path.DirectorySeparatorChar;
}
return path.Substring(basePath.Length);
}
這是這樣,你可以使用它:
static void Main(string[] args)
{
string basePath = @"c:\Projects\";
string file1 = @"c:\Projects\bin\file1.exe";
string file2 = @"c:\Projects\src\folder\file2.exe";
Console.WriteLine(GetRelativeParentPath(basePath, file1));
Console.WriteLine(GetRelativeParentPath(basePath, file2));
}
輸出:
bin
src\folder