TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Uri and UriBuilder Classes

Use the Uri and UriBuilder classes. Store a web address in a Uri instance.
Uri. URI stands for Universal Resource Identifier. You can use the Uri class in the C# programming language to represents URIs such as "https://www.dotnetCodex.com/". You can manage URI data directly with strings.Path

Tip: The Uri class provides a much easier way to access parts of the URI and also manipulate and combine URIs.

Uri example. We show the properties you can access on the Uri instance. First you must create a Uri instance using the Uri constructor. There are overloaded constructors, 2 of which are shown here.

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://dotnetCodex.com/"); Uri uri2 = new Uri(uri1, "/datagridview-tips"); Uri uri3 = new Uri("http://dotnetCodex.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)); } } Output AbsolutePath = / AbsoluteUri = http://dotnetCodex.com/ Authority = dotnetCodex.com DnsSafeHost = dotnetCodex.com Fragment = Host = dotnetCodex.com HostNameType = Dns IsAbsoluteUri = True IsDefaultPort = True IsFile = False IsLoopback = False IsUnc = False LocalPath = / OriginalString = http://dotnetCodex.com/ PathAndQuery = / Port = 80 Query = Scheme = http Segments = / UserEscaped = False UserInfo = ---------------------------------------- AbsolutePath = /datagridview-tips AbsoluteUri = http://dotnetCodex.com/datagridview-tips Authority = dotnetCodex.com DnsSafeHost = dotnetCodex.com Fragment = Host = dotnetCodex.com HostNameType = Dns IsAbsoluteUri = True IsDefaultPort = True IsFile = False IsLoopback = False IsUnc = False LocalPath = /datagridview-tips OriginalString = http://dotnetCodex.com/datagridview-tips PathAndQuery = /datagridview-tips Port = 80 Query = Scheme = http Segments = /,datagridview-tips UserEscaped = False UserInfo = ---------------------------------------- AbsolutePath = /Test/Exists.html AbsoluteUri = http://dotnetCodex.com/Test/Exists.html?good=true Authority = dotnetCodex.com DnsSafeHost = dotnetCodex.com Fragment = Host = dotnetCodex.com HostNameType = Dns IsAbsoluteUri = True IsDefaultPort = True IsFile = False IsLoopback = False IsUnc = False LocalPath = /Test/Exists.html OriginalString = http://dotnetCodex.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 "http://dotnetCodex.com/" is a base URI of "http://dotnetCodex.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://dotnetCodex.com/"); Uri uri2 = new Uri("http://dotnetCodex.com/test/"); if (uri1.IsBaseOf(uri2)) { Console.WriteLine(true); // Written. } if (uri2.IsBaseOf(uri1)) { Console.WriteLine(false); // Not written. } } } Output True
GetLeftPart. Left parts include the scheme, the URI authority, the full path, and the full path and the query string. When you pass the argument UriPartial.Scheme to the GetLeftPart method, then, you will receive just 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://dotnetCodex.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)); } } Output http://dotnetCodex.com http://dotnetCodex.com/test/ http://dotnetCodex.com/test/?cat=1 http://
MakeRelativeUri. When we go from a more deeply nested directory to a higher level directory, the MakeRelativeUri method returns a relative path to indicate upwards traversal. MakeRelativeUri also returns the relative URI in the opposite direction.

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://dotnetCodex.com/"); Uri uri2 = new Uri("http://dotnetCodex.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)); } } Output uri2 to uri1 = ../ uri1 to uri2 = Sort/Test.html
Scheme string. For completeness, this example 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); } } Output :// file ftp gopher http https mailto net.pipe net.tcp news nntp
CheckHostName. Next, we examine some validation methods on the Uri type: the two static methods 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.

C# program that uses CheckHostName and CheckSchemeName using System; class Program { static void Main() { // Use CheckHostName and CheckSchemeName methods. Console.WriteLine(Uri.CheckHostName("dotnetCodex.com")); Console.WriteLine(Uri.CheckSchemeName("http")); Console.WriteLine(Uri.CheckSchemeName(":)")); } } Output Dns True False
CheckHostName, as revealed in IL Disassembler, is an unsafe parsing routine and it simply validates IP addresses. It supports IPv4 and IPv6 as well as DNS names, such as the one shown in the above example.
CheckSchemeName scans for invalid characters in the scheme part of a URI. So you cannot use a smiley face as the scheme, but you can use schemes that might not be used anywhere in the real world.
TryCreate. Continuing on, the TryCreate static method on the Uri type 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://dotnetCodex.com/", UriKind.Absolute, out uri1)) { Console.WriteLine("1 = {0}", uri1); // Reached. } Uri uri2; if (Uri.TryCreate("http:dotnetCodex-com", UriKind.Absolute, out uri2)) { Console.WriteLine("2 = {0}", uri2); // Not reached. } } } Output 1 = http://dotnetCodex.com/
Hex. The Uri type also provides some helper methods for hexadecimal characters and strings. Hexidecimal is an alternative representation of values and when you browse the web, you often see hex characters in URIs.

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); } } Output 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. This is an alternative to the TryCreate method.

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://dotnetCodex.com/test", UriKind.Absolute); bool b = Uri.IsWellFormedUriString("http:testcom-net", UriKind.Absolute); // Display bools. Console.WriteLine(a); Console.WriteLine(b); } } Output 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 some program contexts that involve 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.dotnetCodex.com"); Console.WriteLine(u1.ToString()); // Use UriBuilder properties. UriBuilder u2 = new UriBuilder(); u2.Host = "www.dotnetCodex.com"; u2.Path = "uribuilder"; u2.Scheme = "http"; // Same as "http://" Console.WriteLine(u2.ToString()); // Convert to Uri. Uri uri = u2.Uri; } } Output http://www.dotnetCodex.com/ http://www.dotnetCodex.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.

Tip: You do not need to worry about the punctuation characters here. The UriBuilder will resolve many patterns.

Summary. The Uri class, part of the System namespace, provides a powerful abstraction for simplifying and unifying URI manipulations and selections. It is imposing at first due to its many methods and properties.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf