计算相对文件路径
我有2个文件:
C:Program FilesMyAppimagesimage.png C:UsersStevemedia.jpg
现在我想计算相对于文件1的文件2的文件路径(media.jpg):
......UsersSteve
.NET中是否有内置函数来执行此操作?
使用:
var s1 = @"C:UsersStevemedia.jpg"; var s2 = @"C:Program FilesMyAppimagesimage.png"; var uri = new Uri(s2); var result = uri.MakeRelativeUri(new Uri(s1)).ToString();
没有内置的.NET,但有本机function。 像这样用它:
[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 );
或者如果你仍然喜欢托管代码,那么试试这个:
上述就是C#学习教程:计算相对文件路径分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public static string GetRelativePath(FileSystemInfo path1, FileSystemInfo path2) { if (path1 == null) throw new ArgumentNullException("path1"); if (path2 == null) throw new ArgumentNullException("path2"); Func 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; }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1039066.html