c#如何获取相对路径

   2024-10-01 8620
核心提示:要获取相对路径,可以使用以下方法:使用 System.IO.Path.GetRelativePath 方法来获取相对路径。string relativePath = System.I

要获取相对路径,可以使用以下方法:

使用 System.IO.Path.GetRelativePath 方法来获取相对路径。

string relativePath = System.IO.Path.GetRelativePath(basePath, targetPath);

使用 System.IO.Path.GetDirectoryName 方法获取目标路径的父目录,然后使用 System.IO.Path.GetRelativePath 方法获取相对路径。

string basePath = @"C:\BaseFolder";string targetPath = @"C:\BaseFolder\SubFolder\file.txt";string relativePath = System.IO.Path.GetRelativePath(System.IO.Path.GetDirectoryName(basePath), targetPath);

使用自定义方法来计算相对路径。

public static string GetRelativePath(string fromPath, string toPath){    Uri fromUri = new Uri(fromPath);    Uri toUri = new Uri(toPath);    Uri relativeUri = fromUri.MakeRelativeUri(toUri);    return Uri.UnescapeDataString(relativeUri.ToString());}string basePath = @"C:\BaseFolder";string targetPath = @"C:\BaseFolder\SubFolder\file.txt";string relativePath = GetRelativePath(basePath, targetPath);

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号