Va bene così nel mio caso non ho alcuni dei casi più difficili (fullPath e relativePath che mescolano le posizioni delle mappe di rete, i nomi di file super lunghi). Quello che ho finito è stato creare la classe sotto
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);
}
}
Sembra funzionare piuttosto bene. Almeno, passa questi test 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");
}
}
I casi di test si basano su determinati file esistenti .. questi file sono comuni sulla maggior parte Windows installa ma la vostra situazione potrebbe essere diversa.
fonte
2009-10-28 00:36:13
I percorsi si trovano sulla stessa macchina? Se non normalizzare potrebbe essere difficile. Vedi http://stackoverflow.com/questions/684684/normalize-file-path-with-winapi/684787 –
Il buon punto è uno scenario difficile quando un percorso è un'unità di rete mappata e l'altro un percorso file locale sulla stessa unità . Fortunatamente non è uno scenario con cui dovrei confrontarmi. –
Rick Strahl ha una soluzione che utilizza la classe Uri: http://west-wind.com/weblog/posts/857279.aspx –