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

如何组合URI

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

    我将两个URI对象传递到一些代码中,一个是目录,另一个是文件名(或相对路径)。

    var a = new Uri("file:///C:/Some/Dirs");
    var b = new Uri("some.file");
    

    当我尝试像这样组合它们时:

    var c = new Uri(a,b);
    

    我得到

    file:///C:/Some/some.file

    在那里我希望得到和 Path.Combine (因为这是我需要替换的旧代码):

    file:///C:/Some/Dirs/some.file

    我想不出一个干净的解决办法。

    丑陋的解决方案是添加 / 如果它不在那里的话

    string s = a.OriginalString;
    if(s[s.Length-1] != '/')
       a = new Uri(s + "/");
    
    5 回复  |  直到 10 年前
        1
  •  16
  •   Jon Skeet    16 年前

    好吧,你得告诉URI 以某种方式 最后一部分是目录而不是文件。对我来说,使用尾随斜杠似乎是最明显的方法。

    记住,对于许多URI,您得到的答案是完全正确的。例如,如果Web浏览器正在呈现

    http://foo.com/bar/index.html
    

    它会看到一个“other.html”的相对链接,然后转到

    http://foo.com/bar/other.html
    

    http://foo.com/bar/index.html/other.html
    

    在“directory”uri上使用尾随斜杠是一种非常熟悉的方法,它建议相对的uri应该只是追加而不是替换。

        2
  •  20
  •   Julien Roncaglia    10 年前

    这应该可以为您带来以下好处:

    var baseUri = new Uri("http://www.briankeating.net");
    var absoluteUri = new Uri(baseUri, "/api/GetDefinitions");
    

    这个 constructor 遵循标准的相对URI规则,因此 / 重要的是:

    • http://example.net + foo = http://example.net/foo
    • http://example.net/foo/bar + baz = http://example.net/foo/baz
    • http://example.net/foo/ + bar = http://example.net/foo/bar
    • http://example.net/foo + 酒吧 = http://example.net/bar
    • http://example.net/foo/bar/ + /baz = http://example.net/baz
        3
  •  5
  •   Angelo Nodari    15 年前

    你可以试试这个扩展方法!永远工作!;-)

     public static class StringExtension
        {
            public static string UriCombine(this string str, string param)
            {
                if (!str.EndsWith("/"))
                {
                    str = str + "/";
                }
                var uri = new Uri(str);
                return new Uri(uri, param).AbsoluteUri;
            }
        }
    

    安杰洛,亚历山德罗

        4
  •  2
  •   Tolgahan Albayrak    16 年前

    添加第一个uri的斜线结尾,uri将忽略多个斜线(/)

    var a = new Uri("file:///C:/Some/Dirs/");
    

    编辑:

    var a = new Uri("file:///C:/Some/Dirs");
    var b = new Uri("some.file",  UriKind.Relative);
    var c = new Uri(Path.Combine(a.ToString(), b.ToString()));
    MessageBox.Show(c.AbsoluteUri);
    
        5
  •  0
  •   rama-jka toti    16 年前

    为什么不直接从URI继承并使用它,即在构造函数中执行修复它所需的操作?如果这是程序集内部的或在可及范围内,重构是便宜的。