好吧,在我的情況下,我沒有一些更強硬的邊緣情況(fullPath和relativePath混合網絡地圖位置,超長文件名)。我最終做的是創建下面的類
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安裝,但您的里程可能會有所不同常見的某些文件。
在同一臺機器上的路徑?如果不正常化可能會很棘手。見http://stackoverflow.com/questions/684684/normalize-file-path-with-winapi/684787 – 2009-10-27 19:36:32
好一點那是一個困難的情況下,當一個路徑是網絡映射驅動器和其他本地文件路徑相同的驅動器上。幸運的是,這不是我不得不面對的情況。 – 2009-10-27 20:50:28
裏克施特拉爾具有使用Uri類的解決方案:http://west-wind.com/weblog/posts/857279.aspx – 2010-12-22 10:30:01