Uri
URI stands for Universal Resource Identifier. We can use the Uri
class
in the C# programming language to represents URIs. This helps for strings starting with "http."
In C# programs, you can manage URI data directly with strings. But IndexOf
and Substring
often involve bugs and errors. The Uri
class
simplifies this problem.
Uri
exampleWe show the properties you can access on the Uri
instance. First we must create a Uri
instance using the Uri
constructor (new Uri
).
Uri
instance and print them to the screen.Uri
object.using System; Uri uri = new Uri("https://www.dotnetperls.com/"); // Print properties of Uri instance. Console.WriteLine("AbsolutePath = {0}", uri.AbsolutePath); Console.WriteLine("AbsoluteUri = {0}", uri.AbsoluteUri); Console.WriteLine("Authority = {0}", uri.Authority); Console.WriteLine("DnsSafeHost = {0}", uri.DnsSafeHost); Console.WriteLine("Fragment = {0}", uri.Fragment); Console.WriteLine("Host = {0}", uri.Host); Console.WriteLine("HostNameType = {0}", uri.HostNameType); Console.WriteLine("IsAbsoluteUri = {0}", uri.IsAbsoluteUri); Console.WriteLine("IsDefaultPort = {0}", uri.IsDefaultPort); Console.WriteLine("IsFile = {0}", uri.IsFile); Console.WriteLine("IsLoopback = {0}", uri.IsLoopback); Console.WriteLine("IsUnc = {0}", uri.IsUnc); Console.WriteLine("LocalPath = {0}", uri.LocalPath); Console.WriteLine("OriginalString = {0}", uri.OriginalString); Console.WriteLine("PathAndQuery = {0}", uri.PathAndQuery); Console.WriteLine("Port = {0}", uri.Port); Console.WriteLine("Query = {0}", uri.Query); Console.WriteLine("Scheme = {0}", uri.Scheme); Console.WriteLine("Segments = {0}", string.Join(",", uri.Segments)); Console.WriteLine("UserEscaped = {0}", uri.UserEscaped); Console.WriteLine("UserInfo = {0}", uri.UserInfo);AbsolutePath = / AbsoluteUri = https://www.dotnetperls.com/ Authority = www.dotnetperls.com DnsSafeHost = www.dotnetperls.com Fragment = Host = www.dotnetperls.com HostNameType = Dns IsAbsoluteUri = True IsDefaultPort = True IsFile = False IsLoopback = False IsUnc = False LocalPath = / OriginalString = https://www.dotnetperls.com/ PathAndQuery = / Port = 443 Query = Scheme = https Segments = / UserEscaped = False UserInfo =
IsBaseOf
One useful method on the Uri
class
instance is the IsBaseOf
method. This method lets you determine if one Uri
is contained at the start of the second Uri
.
dotnetperls.com
/" is a base URI of "http://dotnetperls.com
/test/".Console.WriteLine
to print the results to the screen.using System; // Two example Uri instances. Uri uri1 = new Uri("http://dotnetperls.com/"); Uri uri2 = new Uri("http://dotnetperls.com/test/"); if (uri1.IsBaseOf(uri2)) { Console.WriteLine(true); // Written. } if (uri2.IsBaseOf(uri1)) { Console.WriteLine(false); // Not written. }True
GetLeftPart
Left parts include the scheme, the URI authority, the full path, and the full path and the query string
. The argument UriPartial.Scheme
will return the scheme "http://".
UriPartial.Authority
, Path
, and Query arguments reveal longer parts of the left of the URI.using System; // An example Uri instance. Uri uri = new Uri("http://dotnetperls.com/test/?cat=1"); // Test the GetLeftPart method. Console.WriteLine(uri.GetLeftPart(UriPartial.Authority)); Console.WriteLine(uri.GetLeftPart(UriPartial.Path)); Console.WriteLine(uri.GetLeftPart(UriPartial.Query)); Console.WriteLine(uri.GetLeftPart(UriPartial.Scheme));http://dotnetperls.com http://dotnetperls.com/test/ http://dotnetperls.com/test/?cat=1 http://
MakeRelativeUri
We often go from a more deeply nested directory to a higher level directory. MakeRelativeUri
returns a relative path to indicate traversal.
MakeRelativeUri
method on the Uri
instance.using System; // Two absolute Uri instances. Uri uri1 = new Uri("http://dotnetperls.com/"); Uri uri2 = new Uri("http://dotnetperls.com/Sort/Test.html"); // Get relative paths between them in both directions. Console.WriteLine("uri2 to uri1 = {0}", uri2.MakeRelativeUri(uri1)); Console.WriteLine("uri1 to uri2 = {0}", uri1.MakeRelativeUri(uri2));uri2 to uri1 = ../ uri1 to uri2 = Sort/Test.html
string
This program prints out the values of all the scheme strings that are found on the Uri
type in the .NET Framework. You can see that the standard scheme delimiter is "://".
UriScheme
* properties are what you would expect to see. They do not include any trailing delimiters.using System; // Print out the scheme delimiter. // ... Then print out the various schemes. Console.WriteLine(Uri.SchemeDelimiter); Console.WriteLine(Uri.UriSchemeFile); Console.WriteLine(Uri.UriSchemeFtp); Console.WriteLine(Uri.UriSchemeGopher); Console.WriteLine(Uri.UriSchemeHttp); Console.WriteLine(Uri.UriSchemeHttps); Console.WriteLine(Uri.UriSchemeMailto); Console.WriteLine(Uri.UriSchemeNetPipe); Console.WriteLine(Uri.UriSchemeNetTcp); Console.WriteLine(Uri.UriSchemeNews); Console.WriteLine(Uri.UriSchemeNntp);:// file ftp gopher http https mailto net.pipe net.tcp news nntp
CheckHostName
We test CheckHostName
and CheckSchemeName
. These methods serve as parsing validation routines, in that they verify the syntax of the argument.
CheckHostName
is an unsafe parsing routine and it validates IP addresses. It supports IPv4 and IPv6 as well as DNS names.CheckSchemeName
scans for invalid characters in the scheme part of a URI. It will not accept a smiley face as the scheme.using System; // Use CheckHostName and CheckSchemeName methods. Console.WriteLine(Uri.CheckHostName("dotnetperls.com")); Console.WriteLine(Uri.CheckSchemeName("http")); Console.WriteLine(Uri.CheckSchemeName(":)"));Dns True False
TryCreate
This method uses the tester-doer pattern to construct Uri
objects. This is ideal if you do not know if the string
you are using is a valid URI.
UriKind.Relative
or RelativeOrAbsolute
, you will often get a valid URI even if the syntax is strange.using System; Uri uri1; if (Uri.TryCreate("http://dotnetperls.com/", UriKind.Absolute, out uri1)) { Console.WriteLine("1 = {0}", uri1); // Reached. } Uri uri2; if (Uri.TryCreate("http:dotnetperls-com", UriKind.Absolute, out uri2)) { Console.WriteLine("2 = {0}", uri2); // Not reached. }1 = http://dotnetperls.com/
The Uri
type also provides some helper methods for hexadecimal characters and strings. Hexadecimal is an alternative representation of values.
FromHex
, HexEscape
, and IsHexDigit
methods. There are several more on the Uri
type as well.using System; // Use hex methods. int value = Uri.FromHex('A'); string escape = Uri.HexEscape(' '); bool hex = Uri.IsHexDigit('A'); // Print. Console.WriteLine(value); Console.WriteLine(escape); Console.WriteLine(hex);10 %20 True
IsWellFormedUriString
How can you determine if you have a well-formed URI if it is represented as a string
? You can use the IsWellFormedUriString
method on the Uri
type.
IsWellFormedUriString
method returns a bool
value that indicates if the string
argument represents a valid URI.using System; // Use IsWellFormedUriString method. bool a = Uri.IsWellFormedUriString("http://dotnetperls.com/test", UriKind.Absolute); bool b = Uri.IsWellFormedUriString("http:testcom-net", UriKind.Absolute); // Display bools. Console.WriteLine(a); Console.WriteLine(b);True False
UriBuilder
This creates URIs from their individual parts. It handles every URI part, including the host name, path and port. It is useful in code that involves URI creation.
schemeName
and the hostName
.Uri
by setting the Host, Path
and Scheme properties directly. Finally, we show how to convert a UriBuilder
to a Uri
.using System; // 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;http://www.dotnetperls.com/ http://www.dotnetperls.com/uribuilder
UriBuilder
We find some interesting behavior with the UriBuilder
. The Scheme can be set to "http" or "http://" and it will have the same result.
UriBuilder
has some logic internally to make it more compatible. You do not need to worry about the punctuation characters here.The Uri
class
, part of the System
namespace, provides a powerful abstraction for simplifying and unifying URI manipulations and selections. It has many methods and properties.