有没有可靠的方法来计算 Path.Combine() 的逆?
Path.Combine("c:\folder", "subdirectory\something.txt") 可能会返回类似“c:\folder\subdirectory\something.text”的内容。我想要的是相反的函数,其中 Path.GetRelativeUrl("c:\folder", "c:\folder\subdirectory\something.text") 将返回类似“”subdirectory\something.txt”的内容。
一种解决方案是进行字符串比较并修剪根,但是当以不同方式表达相同路径时(在路径表达式中使用“..”或“~1”),这将不起作用。
好吧,就我而言,我没有一些更困难的边缘情况(完整路径和相对路径混合网络地图位置、超长文件名)。我最终做的是创建下面的课程
public class PathUtil
{
static public string NormalizeFilepath(string filepath)
{
string result = System.IO.Path.GetFullPath(filepath).ToLowerInvariant();
result = result.TrimEnd(new [] { '\\' });
return result;
}
public static string GetRelativePath(string rootPath, string fullPath)
{
rootPath = NormalizeFilepath(rootPath);
fullPath = NormalizeFilepath(fullPath);
if (!fullPath.StartsWith(rootPath))
throw new Exception("Could not find rootPath in fullPath when calculating relative path.");
return "." + fullPath.Substring(rootPath.Length);
}
}
看起来效果很好。至少,它通过了这些 NUnit 测试:
[TestFixture]
public class PathUtilTest
{
[Test]
public void TestDifferencesInCapitolizationDontMatter()
{
string format1 = PathUtil.NormalizeFilepath("c:\\windows\\system32");
string format2 = PathUtil.NormalizeFilepath("c:\\WindowS\\System32");
Assert.AreEqual(format1, format2);
}
[Test]
public void TestDifferencesDueToBackstepsDontMatter()
{
string format1 = PathUtil.NormalizeFilepath("c:\\windows\\system32");
string format2 = PathUtil.NormalizeFilepath("c:\\Program Files\\..\\Windows\\System32");
Assert.AreEqual(format1, format2);
}
[Test]
public void TestDifferencesInFinalSlashDontMatter()
{
string format1 = PathUtil.NormalizeFilepath("c:\\windows\\system32");
string format2 = PathUtil.NormalizeFilepath("c:\\windows\\system32\\");
Console.WriteLine(format1);
Console.WriteLine(format2);
Assert.AreEqual(format1, format2);
}
[Test]
public void TestCanCalculateRelativePath()
{
string rootPath = "c:\\windows";
string fullPath = "c:\\windows\\system32\\wininet.dll";
string expectedResult = ".\\system32\\wininet.dll";
string result = PathUtil.GetRelativePath(rootPath, fullPath);
Assert.AreEqual(expectedResult, result);
}
[Test]
public void TestThrowsExceptionIfRootDoesntMatchFullPath()
{
string rootPath = "c:\\windows";
string fullPath = "c:\\program files\\Internet Explorer\\iexplore.exe";
try
{
PathUtil.GetRelativePath(rootPath, fullPath);
}
catch (Exception)
{
return;
}
Assert.Fail("Exception expected");
}
}
测试用例依赖于现有的某些文件。这些文件在大多数 Windows 安装中都很常见,但您的情况可能会有所不同。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)