How to build URIs with the UriBuilder class in C#
April 28, 2015 5 Comments
You can normally use the URI object to construct URIs in C#. However, there’s an object called UriBuilder which lets you build up a URI from various elements.
Here’s an example to construct a simple HTTP address with a scheme, a host and a path:
UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Scheme = "http"; uriBuilder.Host = "cnn.com"; uriBuilder.Path = "americas"; Uri uri = uriBuilder.Uri;
uri will be “http://cnn.com/americas”
…and here’s en extended example for more complex URIs with a port number, a query string, a username and a password:
UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Scheme = "http"; uriBuilder.Host = "www.cnn.com"; uriBuilder.Path = "americas"; uriBuilder.Port = 8089; uriBuilder.UserName = "andras"; uriBuilder.Password = "secret"; uriBuilder.Query = "search=usa";
uri will be “http://andras:secret@www.cnn.com:8089/americas?search=usa”
You can even build URIs that point to a file:
UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Scheme = "c"; uriBuilder.Host = @"temp"; uriBuilder.Path = "log.txt";
…where uri will become “file:///c://temp/log.txt”.
Here’s an example to build a UNC path if you’d like a URI that points to a file share:
UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Scheme = "file"; uriBuilder.Host = @"fileshare"; uriBuilder.Path = "log.txt";
…where uri will become “file://fileshare/log.txt”.
View all various C# language feature related posts here.
Good one
Where does the “”” come from?
err, I don’t know, sometimes WordPress formats text in strange ways. Thanks for the feedback, I’ll update the post. //Andras
this is very strange, I simply can’t get rid of it… There’s definitely no extra character after the “search=usa” bit in the post edit view, it’s somehow added by WP after saving the text.
Looks like whatever you are pasting your text from is changing from standard double-quotes to stylized “right double quote”, which is confusing wordpress. Try ” instead (Hopefully this didn’t eat that…)