c#如何获取相对路径

avatar
作者
筋斗云
阅读量:0

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

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

    string relativePath = System.IO.Path.GetRelativePath(basePath, targetPath); 
  2. 使用 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); 
  3. 使用自定义方法来计算相对路径。

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!