How to combine URIs

前端 未结 5 1442
情话喂你
情话喂你 2020-12-15 17:54

I have two Uri objects passed into some code, one is a directory and the other is a filename (or a relative path)

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


        
相关标签:
5条回答
  • 2020-12-15 18:21

    This should do the trick for you:

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

    This constructor follow the standard relative URI rules so the / are important :

    • 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 + bar = http://example.net/bar
    • http://example.net/foo/bar/ + /baz = http://example.net/baz
    0 讨论(0)
  • 2020-12-15 18:35

    You can try this extension method! Works always! ;-)

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

    Angelo, Alessandro

    0 讨论(0)
  • 2020-12-15 18:35

    add a slash end of your first uri, URI will ignore more than one slash (/)

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

    EDIT:

    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);
    
    0 讨论(0)
  • 2020-12-15 18:37

    Well, you're going to have to tell the Uri somehow that the last part is a directory rather than a file. Using a trailing slash seems to be the most obvious way to me.

    Bear in mind that for many Uris, the answer you've got is exactly right. For example, if your web browser is rendering

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

    and it sees a relatively link of "other.html" it then goes to

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

    not

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

    Using a trailing slash on "directory" Uris is a pretty familiar way of suggesting that relative Uris should just append instead of replacing.

    0 讨论(0)
  • 2020-12-15 18:44

    Why not just inherit from Uri and use that, ie. do in constructor what you need to do to fix it up? Refactoring is cheap assuming this is internal to assembly or within reach..

    0 讨论(0)
提交回复
热议问题