문제

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

사용 : 두 파일 경로가 동일한 파일 (디스크 액세스없이)을 참조하는지 여부를 잘 추측해야합니다. 저의 전형적인 접근 방식은 Makeabsolute 및 PathCanonicalize와 같은 몇 가지 필터를 통해이를 던지고 있으며, 대사율 비교를 수행했습니다.

도움이 되었습니까?

해결책

빠르고 더러운 :

과거에 나는 a fileInfo 경로 문자열에서 객체를 한 다음 FullName 속성을 사용했습니다. 이것은 모든 .. 와. 's를 제거합니다.

물론 당신은 인터 로프 할 수 있습니다 :

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

다른 팁

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;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top