How to get relative path from absolute path

前端 未结 23 2193
既然无缘
既然无缘 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:49

    A bit late to the question, but I just needed this feature as well. I agree with DavidK that since there is a built-in API function that provides this, you should use it. Here's a managed wrapper for it:

    public static string GetRelativePath(string fromPath, string toPath)
    {
        int fromAttr = GetPathAttribute(fromPath);
        int toAttr = GetPathAttribute(toPath);
    
        StringBuilder path = new StringBuilder(260); // MAX_PATH
        if(PathRelativePathTo(
            path,
            fromPath,
            fromAttr,
            toPath,
            toAttr) == 0)
        {
            throw new ArgumentException("Paths must have a common prefix");
        }
        return path.ToString();
    }
    
    private static int GetPathAttribute(string path)
    {
        DirectoryInfo di = new DirectoryInfo(path);
        if (di.Exists)
        {
            return FILE_ATTRIBUTE_DIRECTORY;
        }
    
        FileInfo fi = new FileInfo(path);
        if(fi.Exists)
        {
            return FILE_ATTRIBUTE_NORMAL;
        }
    
        throw new FileNotFoundException();
    }
    
    private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
    private const int FILE_ATTRIBUTE_NORMAL = 0x80;
    
    [DllImport("shlwapi.dll", SetLastError = true)]
    private static extern int PathRelativePathTo(StringBuilder pszPath, 
        string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);
    

提交回复
热议问题