How to build URIs with the UriBuilder class in C#
June 27, 2017 1 Comment
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.
How about “#8221” in URI?