计算相对文件路径

时间:2012-01-30 14:07:17

标签: c# .net file filepath

我有2个文件:

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

C:\Users\Steve\media.jpg

现在我想计算文件2的文件路径(media.jpg)相对于文件1:

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

.NET中是否有内置函数来执行此操作?

2 个答案:

答案 0 :(得分:21)

使用:

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();

答案 1 :(得分:4)

没有内置的.NET,但有本机功能。像这样使用它:

[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
);

或者,如果您仍然喜欢托管代码,请尝试以下方法:

    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;
    }