TheDeveloperBlog.com

Home | Contact Us

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

C# Uri Class

This C# tutorial shows the Uri type. Uri stores a web address. With Uri, we avoid custom parsing code.

URI stands for Universal Resource Identifier.

You can use the Uri class in the C# programming language to represents URIs such as "". You can manage URI data directly with strings.

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

Example. We demonstrate the properties you can access on the Uri instance. First, you must create a Uri instance using the Uri constructor. There are several overloaded constructors, two 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 three 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:///");
	Uri uri2 = new Uri(uri1, "/datagridview-tips");
	Uri uri3 = new Uri("http:///Test/Exists?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:///
Authority = 
DnsSafeHost = 
Fragment =
Host = 
HostNameType = Dns
IsAbsoluteUri = True
IsDefaultPort = True
IsFile = False
IsLoopback = False
IsUnc = False
LocalPath = /
OriginalString = http:///
PathAndQuery = /
Port = 80
Query =
Scheme = http
Segments = /
UserEscaped = False
UserInfo =
----------------------------------------
AbsolutePath = /datagridview-tips
AbsoluteUri = http:///datagridview-tips
Authority = 
DnsSafeHost = 
Fragment =
Host = 
HostNameType = Dns
IsAbsoluteUri = True
IsDefaultPort = True
IsFile = False
IsLoopback = False
IsUnc = False
LocalPath = /datagridview-tips
OriginalString = http:///datagridview-tips
PathAndQuery = /datagridview-tips
Port = 80
Query =
Scheme = http
Segments = /,datagridview-tips
UserEscaped = False
UserInfo =
----------------------------------------
AbsolutePath = /Test/Exists
AbsoluteUri = http:///Test/Exists?good=true
Authority = 
DnsSafeHost = 
Fragment =
Host = 
HostNameType = Dns
IsAbsoluteUri = True
IsDefaultPort = True
IsFile = False
IsLoopback = False
IsUnc = False
LocalPath = /Test/Exists
OriginalString = http:///Test/Exists?good=true
PathAndQuery = /Test/Exists?good=true
Port = 80
Query = ?good=true
Scheme = http
Segments = /,Test/,Exists
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:///" is a base URI of "http:///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:///");
	Uri uri2 = new Uri("http:///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:///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://
http:///test/
http:///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:///");
	Uri uri2 = new Uri("http:///Sort/Test");

	// 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

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(""));
	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.

Tester-Doer

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# that uses TryCreate method

using System;

class Program
{
    static void Main()
    {
	Uri uri1;
	if (Uri.TryCreate("http:///", UriKind.Absolute, out uri1))
	{
	    Console.WriteLine("1 = {0}", uri1); // Reached.
	}
	Uri uri2;
	if (Uri.TryCreate("http:TheDeveloperBlog-com", UriKind.Absolute, out uri2))
	{
	    Console.WriteLine("2 = {0}", uri2); // Not reached.
	}
    }
}

Output

1 = http:///

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# 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# that uses IsWellFormedUriString method

using System;

class Program
{
    static void Main()
    {
	// Use IsWellFormedUriString method.
	bool a = Uri.IsWellFormedUriString("http:///test", UriKind.Absolute);
	bool b = Uri.IsWellFormedUriString("http:testcom-net", UriKind.Absolute);

	// Display bools.
	Console.WriteLine(a);
	Console.WriteLine(b);
    }
}

Output

True
False

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.

However: An understanding of the Uri class can reduce the amount of cumbersome, error-prone code that you have to maintain.


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