Calculate relative Filepath [duplicate]

巧了我就是萌 提交于 2019-11-29 06:07:01

问题


This question already has an answer here:

  • How to get relative path from absolute path 23 answers

I have 2 Files:

C:\Program Files\MyApp\images\image.png

C:\Users\Steve\media.jpg

Now i want to calculate the File-Path of File 2 (media.jpg) relative to File 1:

..\..\..\Users\Steve\

Is there a built-in function in .NET to do this?


回答1:


Use:

var s1 = @"C:\Users\Steve\media.jpg";
var s2 = @"C:\Program Files\MyApp\images\image.png";

var uri = new Uri(s2);

var result = uri.MakeRelativeUri(new Uri(s1)).ToString();



回答2:


There is no built-in .NET, but there is native function. Use it like this:

[DllImport("shlwapi.dll", CharSet=CharSet.Auto)]
static extern bool PathRelativePathTo(
     [Out] StringBuilder pszPath,
     [In] string pszFrom,
     [In] FileAttributes dwAttrFrom,
     [In] string pszTo,
     [In] FileAttributes dwAttrTo
);

Or if you still prefer managed code then try this:

    public static string GetRelativePath(FileSystemInfo path1, FileSystemInfo path2)
    {
        if (path1 == null) throw new ArgumentNullException("path1");
        if (path2 == null) throw new ArgumentNullException("path2");

        Func<FileSystemInfo, string> getFullName = delegate(FileSystemInfo path)
        {
            string fullName = path.FullName;

            if (path is DirectoryInfo)
            {
                if (fullName[fullName.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                {
                    fullName += System.IO.Path.DirectorySeparatorChar;
                }
            }
            return fullName;
        };

        string path1FullName = getFullName(path1);
        string path2FullName = getFullName(path2);

        Uri uri1 = new Uri(path1FullName);
        Uri uri2 = new Uri(path2FullName);
        Uri relativeUri = uri1.MakeRelativeUri(uri2);

        return relativeUri.OriginalString;
    }


来源:https://stackoverflow.com/questions/9065089/calculate-relative-filepath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!