C# UriBuilder

Uri type

UriBuilder creates URIs from their individual parts.
It handles every URI part,
including the host name,
path
and port. It is useful in some program contexts that involve URI creation.

Example

Note

To begin, this program shows two different usages of UriBuilder. In the first instance, we pass two arguments to the constructor. These are received as the schemeName and the hostName.

Next, we compose a Uri by setting the Host, Path and Scheme properties directly. Finally, we show how to convert a UriBuilder to a Uri. This can then be used as an argument to other methods.

Uri Class
Program that uses UriBuilder: C#

using System;

class Program
{
    static void Main()
    {
	// Use UriBuilder constructor.
	UriBuilder u1 = new UriBuilder("http", "www.dotnetperls.com");
	Console.WriteLine(u1.ToString());

	// Use UriBuilder properties.
	UriBuilder u2 = new UriBuilder();
	u2.Host = "www.dotnetperls.com";
	u2.Path = "uribuilder";
	u2.Scheme = "http"; // Same as "http://"
	Console.WriteLine(u2.ToString());

	// Convert to Uri.
	Uri uri = u2.Uri;
    }
}

Output

http://www.dotnetperls.com/
http://www.dotnetperls.com/uribuilder

In this example, we find some interesting behavior with the UriBuilder. The Scheme can be set to "http" or "http://" and it will have the same result. So the UriBuilder has some logic internally to make it more compatible.

Tip:You do not need to worry about the punctuation characters here. The UriBuilder will resolve many patterns.

Summary

With UriBuilder, you can compose URIs through an easy-to-use abstract data type. This alleviates worries about punctuation and reduces certain compatibility issues, such as punctuation characters after the host or scheme.


C#: File: Path