In this tutorial, we will learn how to work with URIs in C# by taking advantage of the URI class. It comes packed with methods and properties to work with URIs. This is very useful when we need to parse and manipulate the URI values.
Syntax:
The following shows the syntax of the URI class in C#:
Basic Usage:
The following shows how to use the URI class to create an instance of the URI class and make a request to the URI using the HttpClient:
public class Program
{
public static void Main()
{
Uri target = new Uri("https://linuxhint.com/");
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, target);
HttpResponseMessage response = client.Send(request);
Console.WriteLine(response.StatusCode);
}
}
In the given example, we made a request to the specified URI and fetch the status code using the response.StatusCode property.
Extracting Parts of URI
The URI comes packed with a lot of properties that allow us to extract the parts of a URI. For example, we can extract things like host, port, absolute path, and more.
Take a look at the following example code:
public class Program
{
public static void Main()
{
Uri target = new Uri("https://linuxhint.com:443/hello=false&format=v");
Console.WriteLine("Host: " + target.Host);
Console.WriteLine("Port: " + target.Port);
Console.WriteLine("Path: " + target.AbsolutePath);
Console.WriteLine("Query: " + target.Query);
}
}
The given code demonstrates how to use the various properties of the URI class to extract specific parts of it.
An example of the resulting output is as follows:
Port: 443
Path: /hello=false&format=v
Query:
UriBuilder Class
We can also use the UriBuilder class to dynamically build the URIs. Take the following example code:
public class Program
{
public static void Main()
{
UriBuilder uriBuilder = new UriBuilder
{
Scheme = "https",
Host = "linuxhint.com",
Path = "/hello",
Query = "format=v"
};
Uri uri = uriBuilder.Uri;
Console.Write(uri.ToString());
}
}
Using the UriBuilder class can help us to dynamically build the URI by individually setting the various components of an URI.
Conclusion
In this tutorial, we learned how to use the URI class in C# to perform the URI operations such as extracting the URI sections, constructing the URIs dynamically, and more.