Home
Search
C# Uri and UriBuilder ClassesUse the Uri and UriBuilder classes. Store a web address in a Uri instance.
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."
Class info. 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.
Path
Uri example. We show the properties you can access on the Uri instance. First we must create a Uri instance using the Uri constructor (new Uri).
Then The Print method accesses the public properties on the Uri instance and prints them to the screen.
And In the output, you can see the different parts of the 3 constructed Uri objects.
C# program that demonstrates Uri class
using System; class Program { static void Main() { // Construct three Uri objects. Uri uri1 = new Uri("http://dotnetperls.com/"); Uri uri2 = new Uri(uri1, "/datagridview-tips"); Uri uri3 = new Uri("http://dotnetperls.com/Test/Exists.html?good=true"); // Write properties. Print(uri1); Print(uri2); Print(uri3); } static void Print(Uri uri) { // 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); Console.WriteLine(new string('-', 40)); } }
AbsolutePath = / AbsoluteUri = http://dotnetperls.com/ Authority = dotnetperls.com DnsSafeHost = dotnetperls.com Fragment = Host = dotnetperls.com HostNameType = Dns IsAbsoluteUri = True IsDefaultPort = True IsFile = False IsLoopback = False IsUnc = False LocalPath = / OriginalString = http://dotnetperls.com/ PathAndQuery = / Port = 80 Query = Scheme = http Segments = / UserEscaped = False UserInfo = ---------------------------------------- AbsolutePath = /datagridview-tips AbsoluteUri = http://dotnetperls.com/datagridview-tips Authority = dotnetperls.com DnsSafeHost = dotnetperls.com Fragment = Host = dotnetperls.com HostNameType = Dns IsAbsoluteUri = True IsDefaultPort = True IsFile = False IsLoopback = False IsUnc = False LocalPath = /datagridview-tips OriginalString = http://dotnetperls.com/datagridview-tips PathAndQuery = /datagridview-tips Port = 80 Query = Scheme = http Segments = /,datagridview-tips UserEscaped = False UserInfo = ---------------------------------------- AbsolutePath = /Test/Exists.html AbsoluteUri = http://dotnetperls.com/Test/Exists.html?good=true Authority = dotnetperls.com DnsSafeHost = dotnetperls.com Fragment = Host = dotnetperls.com HostNameType = Dns IsAbsoluteUri = True IsDefaultPort = True IsFile = False IsLoopback = False IsUnc = False LocalPath = /Test/Exists.html OriginalString = http://dotnetperls.com/Test/Exists.html?good=true PathAndQuery = /Test/Exists.html?good=true Port = 80 Query = ?good=true Scheme = http Segments = /,Test/,Exists.html 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.
So The URI "http://dotnetperls.com/" is a base URI of "http://dotnetperls.com/test/".
However The reverse is not true, as this example shows. It uses Console.WriteLine to print the results to the screen.
C# program that uses IsBaseOf method
using System; class Program { static void Main() { // 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://".
Tip The UriPartial.Authority, Path, and Query arguments reveal longer parts of the left of the URI.
C# program that uses GetLeftPart method
using System; class Program { static void Main() { // 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.
Here We determine a minimal, relative URI between two absolute URIs. We use the MakeRelativeUri method on the Uri instance.
C# program that uses MakeRelativeUri method
using System; class Program { static void Main() { // 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
Scheme 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 "://".
Tip The UriScheme* properties are what you would expect to see. They do not include any trailing delimiters.
Note Some of these schemes, such as Gopher, are obsolete. I would be shocked if you ever needed to use them.
C# program that prints scheme string properties
using System; class Program { static void Main() { // 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.
Note They will not do any further validation than that. The scheme name "doesnotexist" will be considered a valid scheme name.
Info CheckHostName is an unsafe parsing routine and it validates IP addresses. It supports IPv4 and IPv6 as well as DNS names.
Finally CheckSchemeName scans for invalid characters in the scheme part of a URI. It will not accept a smiley face as the scheme.
C# program that uses CheckHostName and CheckSchemeName
using System; class Program { static void Main() { // 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.
Caution If you specify UriKind.Relative or RelativeOrAbsolute, you will often get a valid URI even if the syntax is strange.
Note Relative URIs can simply be file names and not include domains or schemes.
C# program that uses TryCreate method
using System; class Program { static void Main() { 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/
Hex. The Uri type also provides some helper methods for hexadecimal characters and strings. Hexidecimal is an alternative representation of values.
And For example, the escaped hexadecimal value "%20" represents the single space character.
Here We demonstrate the FromHex, HexEscape, and IsHexDigit methods. There are several more on the Uri type as well.
C# program that uses Hex methods
using System; class Program { static void Main() { // 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.
Note The IsWellFormedUriString method returns a bool value that indicates if the string argument represents a valid URI.
C# program that uses IsWellFormedUriString method
using System; class Program { static void Main() { // 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.
Example In the first instance, we pass 2 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.
C# program that uses UriBuilder
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; } }
http://www.dotnetperls.com/ http://www.dotnetperls.com/uribuilder
Notes, 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.
So The UriBuilder has some logic internally to make it more compatible. You do not need to worry about the punctuation characters here.
Summary. 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.
Home
© 2007-2021 sam allen.
see site info on the changelog.