How do I resolve a canonical filename in Windows?

前端 未结 8 1368
自闭症患者
自闭症患者 2020-12-29 13:18

If I have a string that resolves to a file path in Windows, is there an accepted way to get a canonical form of the file name?

For example, I\'d like to know whether

相关标签:
8条回答
  • 2020-12-29 13:31

    Using FileInfo (example in C#):

    FileInfo info1 = new FileInfo(@"C:\stuff\things\etc\misc\whatever.txt");
    FileInfo info2 = new FileInfo(@"C:\stuff\things\etc\misc\other\..\whatever.txt");
    if (info1.FullName.Equals(info2.FullName)) {
        Console.WriteLine("yep, they're equal");
    }
    Console.WriteLine(info1.FullName);
    Console.WriteLine(info2.FullName);
    

    Output is:

    yep, they're equal
    C:\stuff\things\etc\misc\whatever.txt
    C:\stuff\things\etc\misc\whatever.txt

    0 讨论(0)
  • 2020-12-29 13:32

    I would use System.IO.Path.GetFullPath. It takes a string as an input (C:\stuff\things\etc\misc\other..\whatever.txt in your case) and will output a string (C:\stuff\things\etc\misc\whatever.txt).

    0 讨论(0)
  • 2020-12-29 13:33

    Short answer: not really.

    There is no simple way to get the canonical name of a file on Windows. Local files can be available via reparse points, via SUBST. Do you want to deal with NTFS junctions? Windows shortcuts? What about \\?\-escaped filenames

    Remote files can be available via mapped drive letter or via UNC. Is that the UNC to the origin server? Are you using DFS? Is the server using reparse points, etc.? Is the server available by more than one name? What about the IP address? Does it have more than one IP address?

    So, if you're looking for something like the inode number on Windows, it ain't there. See, for example, this page.

    0 讨论(0)
  • 2020-12-29 13:38

    GetFinalPathNameByHandle appears to do what your asking for, which is available starting with Windows Vista.

    0 讨论(0)
  • 2020-12-29 13:40

    To get canonical path you should use PathCanonicalize function.

    0 讨论(0)
  • 2020-12-29 13:41

    jheddings has a nice answer, but since you didn't indicate which language you are using, I thought I'd give a Python way to do it that also works from the command line, using os.path.abspath:

    > python -c "import os.path; print os.path.abspath('C:\stuff\things\etc\misc\other\..\whatever.txt')"
    C:\stuff\things\etc\misc\whatever.txt
    
    0 讨论(0)
提交回复
热议问题