C# tutorials > Input/Output (I/O) and Networking > .NET Networking > Working with URIs (`Uri` class)
Working with URIs (`Uri` class)
This tutorial explores how to work with URIs (Uniform Resource Identifiers) in C# using the `Uri` class. We'll cover creating URIs, accessing their components, and common use cases.
Creating a `Uri` Instance
This code snippet demonstrates the most basic way to create a `Uri` object: by passing a string representing the URI to the `Uri` constructor. The `Uri` class then parses the string and represents it as a structured object. Remember to include `using System;` to use the `Uri` class.
using System;
public class UriExample
{
public static void Main(string[] args)
{
// Creating a Uri from a string
string uriString = "https://www.example.com/path/to/resource?query=value#fragment";
Uri uri = new Uri(uriString);
Console.WriteLine("Original URI: " + uri);
}
}
Accessing URI Components
This snippet shows how to access various components of a `Uri` object. The `Uri` class provides properties like `Scheme`, `Host`, `Port`, `AbsolutePath`, `Query`, and `Fragment` to retrieve specific parts of the URI. The `Segments` property returns an array of strings representing the segments of the path.
using System;
public class UriExample
{
public static void Main(string[] args)
{
string uriString = "https://www.example.com/path/to/resource?query=value#fragment";
Uri uri = new Uri(uriString);
Console.WriteLine("Scheme: " + uri.Scheme); // https
Console.WriteLine("Host: " + uri.Host); // www.example.com
Console.WriteLine("Port: " + uri.Port); // 443 (default for HTTPS)
Console.WriteLine("AbsolutePath: " + uri.AbsolutePath); // /path/to/resource
Console.WriteLine("Query: " + uri.Query); // ?query=value
Console.WriteLine("Fragment: " + uri.Fragment); // #fragment
Console.WriteLine("Segments: ");
foreach (string segment in uri.Segments)
{
Console.WriteLine(segment);
}
}
}
Constructing a Relative URI
This example demonstrates how to create a relative URI and combine it with a base URI to form an absolute URI. Using `UriKind.Relative` tells the constructor that the URI string is relative. The second `Uri` constructor (taking a base URI and a relative URI) resolves the relative URI against the base URI.
using System;
public class UriExample
{
public static void Main(string[] args)
{
Uri baseUri = new Uri("https://www.example.com");
Uri relativeUri = new Uri("/another/path", UriKind.Relative);
Uri absoluteUri = new Uri(baseUri, relativeUri);
Console.WriteLine("Base URI: " + baseUri);
Console.WriteLine("Relative URI: " + relativeUri);
Console.WriteLine("Absolute URI: " + absoluteUri); // https://www.example.com/another/path
}
}
Concepts Behind the Snippet
The `Uri` class represents a Uniform Resource Identifier, which is a string of characters that identifies a resource on the internet. It allows you to parse, validate, and manipulate URIs in a structured way. Understanding URI structure (scheme, authority, path, query, fragment) is crucial for web development, API interactions, and data handling.
Real-Life Use Case
A common use case is building URLs for API requests. Imagine you have a base API URL and need to append query parameters dynamically based on user input. The `UriBuilder` class (which works closely with the `Uri` class) is excellent for this. You can also use the `Uri` class to validate URLs provided by users before making requests, preventing security vulnerabilities and unexpected errors.
using System;
using System.Web;
public class UriBuilderExample
{
public static void Main(string[] args)
{
UriBuilder builder = new UriBuilder("https://api.example.com/data");
var query = HttpUtility.ParseQueryString(builder.Query);
query["param1"] = "value1";
query["param2"] = "value2";
builder.Query = query.ToString();
Uri finalUri = builder.Uri;
Console.WriteLine(finalUri); // Output: https://api.example.com/data?param1=value1¶m2=value2
}
}
Best Practices
Interview Tip
Be prepared to discuss the different parts of a URI and how to access them programmatically. Understanding the purpose of the `Uri` class and its relationship to networking concepts is also important. Explain the difference between absolute and relative URIs, and how `UriBuilder` can be used to create URIs dynamically.
When to Use Them
Use the `Uri` class whenever you need to work with URIs in your application. This includes:
Memory Footprint
The `Uri` class itself doesn't typically have a large memory footprint. However, the string representation of the URI can consume significant memory, especially for long URLs with many query parameters. Avoid storing large numbers of long URIs in memory if performance is critical. Consider using caching or streaming techniques.
Alternatives
While the `Uri` class is the standard way to work with URIs in .NET, you could use regular expressions to parse and manipulate URI strings. However, this is generally not recommended because it's less robust and more prone to errors than using the dedicated `Uri` class and `UriBuilder`. Also, for specific protocols (like FTP), there might be specialized classes that offer more functionality, but for general HTTP(S) URIs, `Uri` and `UriBuilder` are preferred.
Pros
Cons
FAQ
-
What is the difference between `Uri` and `UriBuilder`?
The `Uri` class represents a parsed URI and is immutable. The `UriBuilder` class is used to construct and modify URIs. You can create a `Uri` object from a `UriBuilder` instance. -
How do I handle relative URIs?
Use the `UriKind` enumeration when creating a `Uri` object. `UriKind.Relative` indicates a relative URI, `UriKind.Absolute` indicates an absolute URI, and `UriKind.RelativeOrAbsolute` allows either. You can use a base URI to resolve relative URIs to absolute URIs. -
How can I encode/decode URL parameters?
Use the `HttpUtility.UrlEncode` and `HttpUtility.UrlDecode` methods to encode and decode URL parameters, respectively. These methods ensure that special characters are properly encoded for transmission in a URI.