代码之家  ›  专栏  ›  技术社区  ›  BCS

c#键入以处理相对和绝对URI以及本地文件路径

  •  14
  • BCS  · 技术社区  · 16 年前

    我有一个用例,我将处理两个本地文件路径(例如。 c:\foo\bar.txt )和URI的(例如。 http://somehost.com/fiz/baz Path.Combine 还有朋友。

    我是否应该使用现有的C#类型? 这个 Uri type 可能有用,但乍一看,它似乎只是URI。

    1 回复  |  直到 16 年前
        1
  •  29
  •   buræquete Naveen Kocherla    7 年前

    使用Uri类,它似乎可以正常工作。它将任何文件路径转换为`file:///...Uri中的语法。它按预期处理任何Uri,并具有处理相对Uri的能力。这取决于您试图对该路径执行的其他操作。

    string fileName = @"c:\temp\myfile.bmp";
    string relativeFile = @".\woohoo\temp.bmp";
    string addressName = @"http://www.google.com/blahblah.html";
    
    Uri uriFile = new Uri(fileName);
    Uri uriRelative = new Uri(uriFile, relativeFile);
    Uri uriAddress = new Uri(addressName);
    
    Console.WriteLine(uriFile.ToString());
    Console.WriteLine(uriRelative.ToString());
    Console.WriteLine(uriAddress.ToString());
    

    给我这个输出:

    file:///c:/temp/myfile.bmp  
    file:///c:/temp/woohoo/temp.bmp  
    http://www.google.com/blahblah.html