ठीक है तो मेरे मामले में मेरे पास कुछ कठिन किनारे के मामले नहीं हैं (पूर्णपाथ और सापेक्षपाथ मिश्रण नेटवर्क मानचित्र स्थान, सुपर लंबे फ़ाइल नाम)। मैं क्या कर रहा था
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");
}
}
परीक्षण मामलों मौजूदा .. इन फ़ाइलों अधिकांश विंडो स्थापित करता है लेकिन आपका माइलेज भिन्न हो सकते हैं आम हैं कुछ फ़ाइलों पर निर्भर हैं।
स्रोत
2009-10-28 00:36:13
क्या एक ही मशीन पर पथ हैं? यदि सामान्यीकरण सामान्य नहीं हो सकता है। Http://stackoverflow.com/questions/684684/normalize-file-path-with-winapi/684787 –
अच्छा बिंदु यह एक कठिन परिदृश्य है जब एक पथ नेटवर्क मैप ड्राइव होता है और दूसरा एक ही ड्राइव पर स्थानीय फ़ाइल पथ होता है । सौभाग्य से यह एक परिदृश्य नहीं है जिसके साथ मुझे निपटना होगा। –
रिक स्ट्राल के पास उरी कक्षा का उपयोग करने का एक समाधान है: http://west-wind.com/weblog/posts/857279.aspx –