How to build URIs with the UriBuilder class in C#

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.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

5 Responses to How to build URIs with the UriBuilder class in C#

  1. Gokul G says:

    Good one

  2. olivierpons says:

    Where does the “&#8221” come from?

  3. Ben says:

    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…)

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.