Uri Class
URI stands for Uniform Resource Identifier. A URI is a string of characters that identifies a particular resource. Resources can be anything with an identity, such as a document, image, service, or concept. URIs are used to uniquely identify and locate resources on the internet or within a network.
URIs are categorized into two main types: URLs (Uniform Resource Locators) and URNs (Uniform Resource Names).
URL (Uniform Resource Locator)
- A URL is a type of URI that specifies the location of a resource on the internet or a network.
- It typically consists of several components, including the scheme (e.g., "http" or "https"), the host (domain name or IP address), and the path to the resource.
- Example: https://www.example.com/path/to/resource
URN (Uniform Resource Name)
- A URN is a type of URI used to identify a resource by name in a particular namespace uniquely.
- Unlike URLs, URNs are meant to identify resources even if their location changes persistently.
- Example: urn:isbn:0451450523
In .NET, the System.Uri
class is used to represent URIs. You can create a Uri object by passing a URI string to its constructor. The Uri class provides various properties and methods for working with different components of the URI, such as the scheme, host, path, query, and fragment.
Here's a simple example in C#:
// Creating a Uri object
Uri uri = new Uri("https://www.example.com/path/to/resource");
// Accessing components of the URI
Console.WriteLine($"Scheme: {uri.Scheme}");
Console.WriteLine($"Host: {uri.Host}");
Console.WriteLine($"Path: {uri.AbsolutePath}");
Console.WriteLine($"Query: {uri.Query}");
This example demonstrates creating a Uri object from a URL string and accessing different components of the URI using properties like Scheme, Host, AbsolutePath, and Query.
OriginalString and AbsoluteUri have different behaviors.
AbsoluteUri does escaping
Uri uri = new Uri("http://www.example.com/test.aspx?v=hello world");
Console.WriteLine(uri.OriginalString);
// http://www.example.com/test.aspx?v=hello world
Console.WriteLine(uri.AbsoluteUri);
// http://www.example.com/test.aspx?v=hello%20world <-- different
AbsoluteUri doesn't support relative URIs
var uri = new Uri("/test.aspx?v=hello world", UriKind.Relative);
Console.WriteLine(uri.OriginalString);
// /test.aspx?v=hello world
Console.WriteLine(uri.AbsoluteUri);
// InvalidOperationException: This operation is not supported for a relative URI.
Comments