How to get relative path from absolute path

前端 未结 23 1852
既然无缘
既然无缘 2020-11-22 11:52

There\'s a part in my apps that displays the file path loaded by the user through OpenFileDialog. It\'s taking up too much space to display the whole path, but I don\'t want

23条回答
  •  遇见更好的自我
    2020-11-22 12:42

    As Alex Brault points out, especially on Windows, the absolute path (with drive letter and all) is unambiguous and often better.

    Shouldn't your OpenFileDialog use a regular tree-browser structure?

    To get some nomenclature in place, the RefDir is the directory relative to which you want to specify the path; the AbsName is the absolute path name that you want to map; and the RelPath is the resulting relative path.

    Take the first of these options that matches:

    • If you have different drive letters, there is no relative path from RefDir to AbsName; you must use the AbsName.
    • If the AbsName is in a sub-directory of RefDir or is a file within RefDir then simply remove the RefDir from the start of AbsName to create RelPath; optionally prepend "./" (or ".\" since you are on Windows).
    • Find the longest common prefix of RefDir and AbsName (where D:\Abc\Def and D:\Abc\Default share D:\Abc as the longest common prefix; it has to be a mapping of name components, not a simple longest common substring); call it LCP. Remove LCP from AbsName and RefDir. For each path component left in (RefDir - LCP), prepend "..\" to (AbsName - LCP) to yield RelPath.

    To illustrate the last rule (which is, of course, by far the most complex), start with:

    RefDir = D:\Abc\Def\Ghi
    AbsName = D:\Abc\Default\Karma\Crucible
    

    Then

    LCP = D:\Abc
    (RefDir - LCP) = Def\Ghi
    (Absname - LCP) = Default\Karma\Crucible
    RelPath = ..\..\Default\Karma\Crucible
    

    While I was typing, DavidK produced an answer which suggests that you are not the first to need this feature and that there is a standard function to do this job. Use it. But there's no harm in being able to think your way through from first principles, either.

    Except that Unix systems do not support drive letters (so everything is always located under the same root directory, and the first bullet therefore is irrelevant), the same technique could be used on Unix.

提交回复
热议问题