温馨提示×

c#如何获取相对路径

c#
小亿
278
2024-08-11 13:01:36
栏目: 编程语言
开发者测试专用服务器限时活动,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);
    

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c#相对路径获取的方法是什么

0