2009-03-08 4 views
8

C#에서 PathCanonicalize과 동등한 기능은 무엇입니까?C#에서 PathCanonicalize와 동등한 것

사용 : 두 파일 경로가 동일한 파일을 참조하는지 (디스크 액세스없이) 잘 추측해야합니다. 내 전형적인 접근 방식은 MakeAbsolute 및 PathCanonicalize와 같은 몇 가지 필터를 통해이를 던진 다음 대소 문자를 구분하지 않는 비교를 수행합니다. 신속하고 더러운

답변

12

: 다음 경로 문자열에서 FileInfo 객체를 생성 한 과거

는 전체 이름 속성을 사용했다. 이렇게하면 .. \ '와. \'모두가 제거됩니다.

물론 당신은 상호 운용성 수 :

[DllImport("shlwapi", EntryPoint="PathCanonicalize")] 
    private static extern bool PathCanonicalize(
     StringBuilder lpszDst, 
     string lpszSrc 
    ); 
5

3 솔루션 :

최상의 시나리오, 당신은 호출 프로세스가 파일 시스템에 대한 완전한 액세스 권한을 갖습니다 100 % 확신한다. 주의해야 할 점은 : 생산 상자에 권한은 우리가 항상 무료 아니에요

public static string PathCombineAndCanonicalize1(string path1, string path2) 
    { 
     string combined = Path.Combine(path1, path2); 
     combined = Path.GetFullPath(combined); 
     return combined; 
    } 

까다로운 일이 될 수 있지만. 문자열 연산을 허가없이 수행해야하는 경우가 많습니다. 이것에 대한 원초적인 요구가 있습니다. 주의 : 기본 전화

public static string PathCombineAndCanonicalize2(string path1, string path2) 
    { 
     string combined = Path.Combine(path1, path2); 
     StringBuilder sb = new StringBuilder(Math.Max(260, 2 * combined.Length)); 
     PathCanonicalize(sb, combined); 
     return sb.ToString(); 
    } 

    [DllImport("shlwapi.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    private static extern bool PathCanonicalize([Out] StringBuilder dst, string src); 

세 번째 전략 리조트는 CLR을 속이는 것입니다. Path.GetFullPath()는 가상의 경로에서 정상적으로 작동하므로 항상 하나만 제공하는지 확인하십시오. 당신이 할 수있는 것은 가짜 UNC 경로 루트를 교환하는 것입니다, GetFullPath()를 호출 한 다음에 다시 진짜를 교환 은 경고 :.이 코드 리뷰에 하드 판매 필요할 수 있습니다

public static string PathCombineAndCanonicalize3(string path1, string path2) 
    { 
     string originalRoot = string.Empty; 

     if (Path.IsPathRooted(path1)) 
     { 
      originalRoot = Path.GetPathRoot(path1); 
      path1 = path1.Substring(originalRoot.Length); 
     } 

     string fakeRoot = @"\\thiscantbe\real\"; 
     string combined = Path.Combine(fakeRoot, path1, path2); 
     combined = Path.GetFullPath(combined); 
     combined = combined.Substring(fakeRoot.Length); 
     combined = Path.Combine(originalRoot, combined); 
     return combined; 
    }