Uri Uri Uri Uri Class

Definition

Provides an object representation of a uniform resource identifier (URI) and easy access to the parts of the URI.

public ref class Uri : System::Runtime::Serialization::ISerializable
[System.ComponentModel.TypeConverter(typeof(System.UriTypeConverter))]
[System.Serializable]
public class Uri : System.Runtime.Serialization.ISerializable
type Uri = class
    interface ISerializable
Public Class Uri
Implements ISerializable
Inheritance
Attributes
Implements

Examples

The following example creates an instance of the Uri class and uses it to create a WebRequest instance.

Uri^ siteUri = gcnew Uri( "http://www.contoso.com/" );
WebRequest^ wr = WebRequest::Create( siteUri );
Uri siteUri = new Uri("http://www.contoso.com/");
 
WebRequest wr = WebRequest.Create(siteUri);

Dim siteUri As New Uri("http://www.contoso.com/")
        
Dim wr As WebRequest = WebRequest.Create(siteUri)

Remarks

A URI is a compact representation of a resource available to your application on the intranet or Internet. The Uri class defines the properties and methods for handling URIs, including parsing, comparing, and combining. The Uri class properties are read-only; to create a modifiable object, use the UriBuilder class.

Relative URIs (for example, "/new/index.htm") must be expanded with respect to a base URI so that they are absolute. The MakeRelative method is provided to convert absolute URIs to relative URIs when necessary.

The Uri constructors do not escape URI strings if the string is a well-formed URI including a scheme identifier.

The Uri properties return a canonical data representation in escaped encoding, with all characters with Unicode values greater than 127 replaced with their hexadecimal equivalents. To put the URI in canonical form, the Uri constructor performs the following steps:

  • Converts the URI scheme to lowercase.

  • Converts the host name to lowercase.

  • If the host name is an IPv6 address, the canonical IPv6 address is used. ScopeId and other optional IPv6 data are removed.

  • Removes default and empty port numbers.

  • Converts implicit file paths without the file:// scheme (for example, "C:\my\file") to explicit file paths with the file:// scheme.

  • Escaped characters (also known as percent-encoded octets) that don't have a reserved purpose are decoded (also known as being unescaped). These unreserved characters include uppercase and lowercase letters (%41-%5A and %61-%7A), decimal digits (%30-%39), hyphen (%2D), period (%2E), underscore (%5F), and tilde (%7E).

  • Canonicalizes the path for hierarchical URIs by compacting sequences such as /./, /../, and // (whether or not the sequence is escaped). Note that there are some schemes for which these sequences are not compacted.

  • For hierarchical URIs, if the host is not terminated with a forward slash (/), one is added.

  • By default, any reserved characters in the URI are escaped in accordance with RFC 2396. This behavior changes if International Resource Identifiers or International Domain Name parsing is enabled in which case reserved characters in the URI are escaped in accordance with RFC 3986 and RFC 3987.

As part of canonicalization in the constructor for some schemes, dot-segments and empty segments (/./, /../, and //) are compacted (in other words, they are removed). The schemes for which URI will compact these sequences include http, https, tcp, net.pipe, and net.tcp. For some other schemes, these sequences are not compacted. Here's how this compacting looks in practice.

var uri = new Uri("http://myUrl/../.."); // http scheme, unescaped
OR
var uri = new Uri("http://myUrl/%2E%2E/%2E%2E"); // http scheme, escaped
OR
var uri = new Uri("ftp://myUrl/../.."); // ftp scheme, unescaped
OR
var uri = new Uri("ftp://myUrl/%2E%2E/%2E%2E"); // ftp scheme, escaped

Console.WriteLine(uri.AbsoluteUri);  
Console.WriteLine(uri.PathAndQuery);  

When this code is executed, it returns the following output, with the escaped sequences unescaped if necessary and then compacted.

http://myUrl/  
/  

You can transform the contents of the Uri class from an escape encoded URI reference to a readable URI reference by using the ToString method. Note that some reserved characters might still be escaped in the output of the ToString method. This is to support unambiguous reconstruction of a URI from the value returned by ToString.

Some URIs include a fragment identifier or a query or both. A fragment identifier is any text that follows a number sign (#), not including the number sign; the fragment text is stored in the Fragment property. Query information is any text that follows a question mark (?) in the URI; the query text is stored in the Query property.

In the .NET Framework version 1.1, if the string specified to a constructor contains an unknown scheme and "c:\", the Uri class inserts "//" after the colon. For example, the URI xyz:c:\abc is converted to xyz://c:/abc. In the .NET Framework version 2.0, this behavior has been removed, and the example string is converted to xyz:c:/abc.

Note

The URI class supports the use of IP addresses in both quad-notation for IPv4 protocol and colon-hexadecimal for IPv6 protocol. Remember to enclose the IPv6 address in square brackets, as in http://[::1].

International Resource Identifier Support

Web addresses are typically expressed using uniform resource identifiers that consist of a very restricted set of characters:

  • Upper and lower case ASCII letters from the English alphabet.

  • Digits from 0 to 9.

  • A small number of other ASCII symbols.

The specifications for URIs are documented in RFC 2396, RFC 2732, RFC 3986, and RFC 3987 published by the Internet Engineering Task Force (IETF).

With the growth of the Internet, there is a growing need to identify resources using languages other than English. Identifiers which facilitate this need and allow non-ASCII characters (characters in the Unicode/ISO 10646 character set) are known as International Resource Identifiers (IRIs). The specifications for IRIs are documented in RFC 3987 published by IETF. Using IRIs allows a URL to contain Unicode characters.

The existing Uri class has been extended in .NET Framework v3.5, 3.0 SP1, and 2.0 SP1 to provide IRI support based on RFC 3987. Users of .NET Framework versions before version 4.5 will not see any change from the .NET Framework 2.0 behavior unless they specifically enable IRI. This ensures application compatibility with prior versions of the .NET Framework.

To enable support for IRI, the following change is required:

  • Specify whether you want Internationalized Domain Name (IDN) parsing applied to the domain name and whether IRI parsing rules should be applied. This can be done in the machine.config or in the app.config file. For example, add the following:

    <configuration>  
      <uri>  
      <idn enabled="All" />  
      <iriParsing enabled="true" />  
      </uri>  
    </configuration>  
    

Users of .NET Framework 4.5 and newer always have IRI enabled. IRI parsing cannot be changed using a .config file.

Enabling IDN will convert all Unicode labels in a domain name to their Punycode equivalents. Punycode names contain only ASCII characters and always start with the xn-- prefix. The reason for this is to support existing DNS servers on the Internet, since most DNS servers only support ASCII characters (see RFC 3940).

Enabling IRI and IDN affects the value of the Uri.DnsSafeHost property. Enabling IRI and IDN can also change the behavior of the Equals, OriginalString, GetComponents, and IsWellFormedOriginalString methods.

There are three possible values for IDN depending on the DNS servers that are used:

  • idn enabled = All

    This value will convert any Unicode domain names to their Punycode equivalents (IDN names).

  • idn enabled = AllExceptIntranet

    This value will convert all Unicode domain names not on the local Intranet to use the Punycode equivalents (IDN names). In this case to handle international names on the local Intranet, the DNS servers that are used for the Intranet should support Unicode name resolution.

  • idn enabled = None

    This value will not convert any Unicode domain names to use Punycode. This is the default value which is consistent with the .NET Framework 2.0 behaviour.

When IRI parsing is enabled (iriParsing enabled = true) normalization and character checking are done according to the latest IRI rules in RFC 3986 and RFC 3987. When IRI parsing is disabled, normalization and character checking are performed according to RFC 2396 and RFC 2732 (for IPv6 literals). In versions of the .NET Framework before version 4.5, the default value is false. In .NET Framework version 4.5 and newer, the default value is true, and the enabled state of IRI parsing cannot be modified by settings in a .config file.

IRI and IDN processing in the Uri class can also be controlled using the System.Configuration.IriParsingElement, System.Configuration.IdnElement, and System.Configuration.UriSection configuration setting classes. The System.Configuration.IriParsingElement setting enables or disables IRI processing in the Uri class. The System.Configuration.IdnElement setting enables or disables IDN processing in the Uri class. The System.Configuration.IriParsingElement setting also indirectly controls IDN. IRI processing must be enabled for IDN processing to be possible. If IRI processing is disabled, then IDN processing will be set to the default setting where the .NET Framework 2.0 behavior is used for compatibility and IDN names are not used.

The configuration setting for the System.Configuration.IriParsingElement and System.Configuration.IdnElement will be read once when the first System.Uri class is constructed. Changes to configuration settings after that time are ignored.

The System.GenericUriParser class has also been extended to allow creating a customizable parser that supports IRI and IDN. The behavior of a System.GenericUriParser object is specified by passing a bitwise combination of the values available in the System.GenericUriParserOptions enumeration to the System.GenericUriParser constructor. The GenericUriParserOptions.IriParsing type indicates the parser supports the parsing rules specified in RFC 3987 for International Resource Identifiers (IRI). Whether IRI is used is dictated by the configuration values previously discussed.

The GenericUriParserOptions.Idn type indicates the parser supports Internationalized Domain Name (IDN) parsing (IDN) of host names. Whether IDN is used is dictated by the configuration values previously discussed.

Implicit File Path Support

Uri can also be used to represent local file system paths. These paths can be represented explicitly in URIs that begin with the file:// scheme, and implicitly in URIs that do not have the file:// scheme. As a concrete example, the following two URIs are both valid, and represent the same file path:

Uri uri1 = new Uri("C:/test/path/file.txt") // Implicit file path.
Uri uri2 = new Uri("file:///C:/test/path/file.txt") // Explicit file path.

These implicit file paths are not compliant with the URI specification and so should be avoided when possible. When using .NET Core on Unix-based systems, implicit file paths can be especially problematic, because an absolute implicit file path is indistinguishable from a relative path. When such ambiguity is present, Uri default to interpreting the path as an absolute URI.

Performance Considerations

If you use a *Web.config *file that contains URIs to initialize your application, additional time is required to process the URIs if their scheme identifiers are nonstandard. In such a case, initialize the affected parts of your application when the URIs are needed, not at start time.

Notes to Callers

Because of security concerns, your application should use caution when accepting Uri instances from untrusted sources and with dontEscape set to true.You can check a URI string for validity by calling the IsWellFormedOriginalString() method.

Constructors

Uri(SerializationInfo, StreamingContext) Uri(SerializationInfo, StreamingContext) Uri(SerializationInfo, StreamingContext) Uri(SerializationInfo, StreamingContext)

Initializes a new instance of the Uri class from the specified instances of the SerializationInfo and StreamingContext classes.

Uri(String) Uri(String) Uri(String) Uri(String)

Initializes a new instance of the Uri class with the specified URI.

Uri(String, Boolean) Uri(String, Boolean) Uri(String, Boolean) Uri(String, Boolean)

Initializes a new instance of the Uri class with the specified URI, with explicit control of character escaping.

Uri(String, UriKind) Uri(String, UriKind) Uri(String, UriKind) Uri(String, UriKind)

Initializes a new instance of the Uri class with the specified URI. This constructor allows you to specify if the URI string is a relative URI, absolute URI, or is indeterminate.

Uri(Uri, String) Uri(Uri, String) Uri(Uri, String) Uri(Uri, String)

Initializes a new instance of the Uri class based on the specified base URI and relative URI string.

Uri(Uri, String, Boolean) Uri(Uri, String, Boolean) Uri(Uri, String, Boolean) Uri(Uri, String, Boolean)

Initializes a new instance of the Uri class based on the specified base and relative URIs, with explicit control of character escaping.

Uri(Uri, Uri) Uri(Uri, Uri) Uri(Uri, Uri) Uri(Uri, Uri)

Initializes a new instance of the Uri class based on the combination of a specified base Uri instance and a relative Uri instance.

Fields

SchemeDelimiter SchemeDelimiter SchemeDelimiter SchemeDelimiter

Specifies the characters that separate the communication protocol scheme from the address portion of the URI. This field is read-only.

UriSchemeFile UriSchemeFile UriSchemeFile UriSchemeFile

Specifies that the URI is a pointer to a file. This field is read-only.

UriSchemeFtp UriSchemeFtp UriSchemeFtp UriSchemeFtp

Specifies that the URI is accessed through the File Transfer Protocol (FTP). This field is read-only.

UriSchemeGopher UriSchemeGopher UriSchemeGopher UriSchemeGopher

Specifies that the URI is accessed through the Gopher protocol. This field is read-only.

UriSchemeHttp UriSchemeHttp UriSchemeHttp UriSchemeHttp

Specifies that the URI is accessed through the Hypertext Transfer Protocol (HTTP). This field is read-only.

UriSchemeHttps UriSchemeHttps UriSchemeHttps UriSchemeHttps

Specifies that the URI is accessed through the Secure Hypertext Transfer Protocol (HTTPS). This field is read-only.

UriSchemeMailto UriSchemeMailto UriSchemeMailto UriSchemeMailto

Specifies that the URI is an email address and is accessed through the Simple Mail Transport Protocol (SMTP). This field is read-only.

UriSchemeNetPipe UriSchemeNetPipe UriSchemeNetPipe UriSchemeNetPipe

Specifies that the URI is accessed through the NetPipe scheme used by Windows Communication Foundation (WCF). This field is read-only.

UriSchemeNetTcp UriSchemeNetTcp UriSchemeNetTcp UriSchemeNetTcp

Specifies that the URI is accessed through the NetTcp scheme used by Windows Communication Foundation (WCF). This field is read-only.

UriSchemeNews UriSchemeNews UriSchemeNews UriSchemeNews

Specifies that the URI is an Internet news group and is accessed through the Network News Transport Protocol (NNTP). This field is read-only.

UriSchemeNntp UriSchemeNntp UriSchemeNntp UriSchemeNntp

Specifies that the URI is an Internet news group and is accessed through the Network News Transport Protocol (NNTP). This field is read-only.

Properties

AbsolutePath AbsolutePath AbsolutePath AbsolutePath

Gets the absolute path of the URI.

AbsoluteUri AbsoluteUri AbsoluteUri AbsoluteUri

Gets the absolute URI.

Authority Authority Authority Authority

Gets the Domain Name System (DNS) host name or IP address and the port number for a server.

DnsSafeHost DnsSafeHost DnsSafeHost DnsSafeHost

Gets a host name that, after being unescaped if necessary, is safe to use for DNS resolution.

Fragment Fragment Fragment Fragment

Gets the escaped URI fragment.

Host Host Host Host

Gets the host component of this instance.

HostNameType HostNameType HostNameType HostNameType

Gets the type of the host name specified in the URI.

IdnHost IdnHost IdnHost IdnHost

The RFC 3490 compliant International Domain Name of the host, using Punycode as appropriate. This string, after being unescaped if necessary, is safe to use for DNS resolution.

IsAbsoluteUri IsAbsoluteUri IsAbsoluteUri IsAbsoluteUri

Gets whether the Uri instance is absolute.

IsDefaultPort IsDefaultPort IsDefaultPort IsDefaultPort

Gets whether the port value of the URI is the default for this scheme.

IsFile IsFile IsFile IsFile

Gets a value indicating whether the specified Uri is a file URI.

IsLoopback IsLoopback IsLoopback IsLoopback

Gets whether the specified Uri references the local host.

IsUnc IsUnc IsUnc IsUnc

Gets whether the specified Uri is a universal naming convention (UNC) path.

LocalPath LocalPath LocalPath LocalPath

Gets a local operating-system representation of a file name.

OriginalString OriginalString OriginalString OriginalString

Gets the original URI string that was passed to the Uri constructor.

PathAndQuery PathAndQuery PathAndQuery PathAndQuery

Gets the AbsolutePath and Query properties separated by a question mark (?).

Port Port Port Port

Gets the port number of this URI.

Query Query Query Query

Gets any query information included in the specified URI.

Scheme Scheme Scheme Scheme

Gets the scheme name for this URI.

Segments Segments Segments Segments

Gets an array containing the path segments that make up the specified URI.

UserEscaped UserEscaped UserEscaped UserEscaped

Indicates that the URI string was completely escaped before the Uri instance was created.

UserInfo UserInfo UserInfo UserInfo

Gets the user name, password, or other user-specific information associated with the specified URI.

Methods

Canonicalize() Canonicalize() Canonicalize() Canonicalize()

Converts the internally stored URI to canonical form.

CheckHostName(String) CheckHostName(String) CheckHostName(String) CheckHostName(String)

Determines whether the specified host name is a valid DNS name.

CheckSchemeName(String) CheckSchemeName(String) CheckSchemeName(String) CheckSchemeName(String)

Determines whether the specified scheme name is valid.

CheckSecurity() CheckSecurity() CheckSecurity() CheckSecurity()

Calling this method has no effect.

Compare(Uri, Uri, UriComponents, UriFormat, StringComparison) Compare(Uri, Uri, UriComponents, UriFormat, StringComparison) Compare(Uri, Uri, UriComponents, UriFormat, StringComparison) Compare(Uri, Uri, UriComponents, UriFormat, StringComparison)

Compares the specified parts of two URIs using the specified comparison rules.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Compares two Uri instances for equality.

Escape() Escape() Escape() Escape()

Converts any unsafe or reserved characters in the path component to their hexadecimal character representations.

EscapeDataString(String) EscapeDataString(String) EscapeDataString(String) EscapeDataString(String)

Converts a string to its escaped representation.

EscapeString(String) EscapeString(String) EscapeString(String) EscapeString(String)

Converts a string to its escaped representation.

EscapeUriString(String) EscapeUriString(String) EscapeUriString(String) EscapeUriString(String)

Converts a URI string to its escaped representation.

FromHex(Char) FromHex(Char) FromHex(Char) FromHex(Char)

Gets the decimal value of a hexadecimal digit.

GetComponents(UriComponents, UriFormat) GetComponents(UriComponents, UriFormat) GetComponents(UriComponents, UriFormat) GetComponents(UriComponents, UriFormat)

Gets the specified components of the current instance using the specified escaping for special characters.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Gets the hash code for the URI.

GetLeftPart(UriPartial) GetLeftPart(UriPartial) GetLeftPart(UriPartial) GetLeftPart(UriPartial)

Gets the specified portion of a Uri instance.

GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Returns the data needed to serialize the current instance.

GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
HexEscape(Char) HexEscape(Char) HexEscape(Char) HexEscape(Char)

Converts a specified character into its hexadecimal equivalent.

HexUnescape(String, Int32) HexUnescape(String, Int32) HexUnescape(String, Int32) HexUnescape(String, Int32)

Converts a specified hexadecimal representation of a character to the character.

InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
IsBadFileSystemCharacter(Char) IsBadFileSystemCharacter(Char) IsBadFileSystemCharacter(Char) IsBadFileSystemCharacter(Char)

Gets whether a character is invalid in a file system name.

IsBaseOf(Uri) IsBaseOf(Uri) IsBaseOf(Uri) IsBaseOf(Uri)

Determines whether the current Uri instance is a base of the specified Uri instance.

IsExcludedCharacter(Char) IsExcludedCharacter(Char) IsExcludedCharacter(Char) IsExcludedCharacter(Char)

Gets whether the specified character should be escaped.

IsHexDigit(Char) IsHexDigit(Char) IsHexDigit(Char) IsHexDigit(Char)

Determines whether a specified character is a valid hexadecimal digit.

IsHexEncoding(String, Int32) IsHexEncoding(String, Int32) IsHexEncoding(String, Int32) IsHexEncoding(String, Int32)

Determines whether a character in a string is hexadecimal encoded.

IsReservedCharacter(Char) IsReservedCharacter(Char) IsReservedCharacter(Char) IsReservedCharacter(Char)

Gets whether the specified character is a reserved character.

IsWellFormedOriginalString() IsWellFormedOriginalString() IsWellFormedOriginalString() IsWellFormedOriginalString()

Indicates whether the string used to construct this Uri was well-formed and is not required to be further escaped.

IsWellFormedUriString(String, UriKind) IsWellFormedUriString(String, UriKind) IsWellFormedUriString(String, UriKind) IsWellFormedUriString(String, UriKind)

Indicates whether the string is well-formed by attempting to construct a URI with the string and ensures that the string does not require further escaping.

MakeRelative(Uri) MakeRelative(Uri) MakeRelative(Uri) MakeRelative(Uri)

Determines the difference between two Uri instances.

MakeRelativeUri(Uri) MakeRelativeUri(Uri) MakeRelativeUri(Uri) MakeRelativeUri(Uri)

Determines the difference between two Uri instances.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Parse() Parse() Parse() Parse()

Parses the URI of the current instance to ensure it contains all the parts required for a valid URI.

ToString() ToString() ToString() ToString()

Gets a canonical string representation for the specified Uri instance.

TryCreate(String, UriKind, Uri) TryCreate(String, UriKind, Uri) TryCreate(String, UriKind, Uri) TryCreate(String, UriKind, Uri)

Creates a new Uri using the specified String instance and a UriKind.

TryCreate(Uri, String, Uri) TryCreate(Uri, String, Uri) TryCreate(Uri, String, Uri) TryCreate(Uri, String, Uri)

Creates a new Uri using the specified base and relative String instances.

TryCreate(Uri, Uri, Uri) TryCreate(Uri, Uri, Uri) TryCreate(Uri, Uri, Uri) TryCreate(Uri, Uri, Uri)

Creates a new Uri using the specified base and relative Uri instances.

Unescape(String) Unescape(String) Unescape(String) Unescape(String)

Converts the specified string by replacing any escape sequences with their unescaped representation.

UnescapeDataString(String) UnescapeDataString(String) UnescapeDataString(String) UnescapeDataString(String)

Converts a string to its unescaped representation.

Operators

Equality(Uri, Uri) Equality(Uri, Uri) Equality(Uri, Uri) Equality(Uri, Uri)

Determines whether two Uri instances have the same value.

Inequality(Uri, Uri) Inequality(Uri, Uri) Inequality(Uri, Uri) Inequality(Uri, Uri)

Determines whether two Uri instances do not have the same value.

Explicit Interface Implementations

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Returns the data needed to serialize the current instance.

Applies to

See also