【问题标题】:c# type to handle relative and absolute URI's and local file pathsc# 类型来处理相对和绝对 URI 和本地文件路径
【发布时间】:2010-10-22 09:53:00
【问题描述】:

我有一个用例,我将同时处理本地文件路径(例如c:\foo\bar.txt)和URI(例如http://somehost.com/fiz/baz)。我还将处理相对路径和绝对路径,所以我需要像 Path.Combine 和朋友这样的功能。

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

【问题讨论】:

    标签: c# path types uri


    【解决方案1】:

    使用 Uri 类,它似乎正在工作。它将任何文件路径转换为 ​​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
    

    【讨论】:

    • 那个 file:/// 东西……很不方便,但如果必须的话,我可以忍受。我真的希望为它设置更直接的东西+1
    • 好吧,您可以检查“LocalPath”属性,它会为您提供本地格式的文件名(不包括 file:///)。
    • 非常有帮助!感谢您的快速回答。
    猜你喜欢
    • 2021-06-15
    • 2011-06-30
    • 2018-09-30
    • 2012-09-23
    • 2010-09-15
    • 1970-01-01
    • 2013-07-14
    • 2010-12-17
    • 1970-01-01
    相关资源
    最近更新 更多