5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Garrett Rooney (rooneg@electricjellyfish.net)
7 // Ian MacLean (ianm@activestate.com)
8 // Ben Maurer (bmaurer@users.sourceforge.net)
9 // Atsushi Enomoto (atsushi@ximian.com)
10 // Sebastien Pouliot <sebastien@ximian.com>
11 // Stephane Delcroix <stephane@delcroix.org>
13 // (C) 2001 Garrett Rooney
14 // (C) 2003 Ian MacLean
15 // (C) 2003 Ben Maurer
16 // Copyright (C) 2003,2009 Novell, Inc (http://www.novell.com)
17 // Copyright (c) 2009 Stephane Delcroix
19 // Permission is hereby granted, free of charge, to any person obtaining
20 // a copy of this software and associated documentation files (the
21 // "Software"), to deal in the Software without restriction, including
22 // without limitation the rights to use, copy, modify, merge, publish,
23 // distribute, sublicense, and/or sell copies of the Software, and to
24 // permit persons to whom the Software is furnished to do so, subject to
25 // the following conditions:
27 // The above copyright notice and this permission notice shall be
28 // included in all copies or substantial portions of the Software.
30 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
31 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
33 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
34 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
35 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
36 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 // See RFC 2396 for more info on URI's.
40 // TODO: optimize by parsing host string only once
42 using System.ComponentModel;
45 using System.Runtime.Serialization;
47 using System.Collections;
48 using System.Collections.Generic;
49 using System.Globalization;
52 // Disable warnings on Obsolete methods being used
54 #pragma warning disable 612
59 [TypeConverter (typeof (UriTypeConverter))]
60 public class Uri : ISerializable {
62 // o scheme excludes the scheme delimiter
63 // o port is -1 to indicate no port is defined
64 // o path is empty or starts with / when scheme delimiter == "://"
65 // o query is empty or starts with ? char, escaped.
66 // o fragment is empty or starts with # char, unescaped.
67 // o all class variables are in escaped format when they are escapable,
68 // except cachedToString.
69 // o UNC is supported, as starts with "\\" for windows,
72 private string source;
73 private string scheme = String.Empty;
74 private string host = String.Empty;
75 private int port = -1;
76 private string path = String.Empty;
77 private string query = String.Empty;
78 private string fragment = String.Empty;
79 private string userinfo;
81 private bool isAbsoluteUri = true;
82 private long scope_id;
84 private List<string> segments;
86 private bool userEscaped;
87 private string cachedAbsoluteUri;
88 private string cachedToString;
89 private string cachedLocalPath;
90 private int cachedHashCode;
92 private static bool s_IriParsing;
94 internal static bool IriParsing {
95 get { return s_IriParsing; }
96 set { s_IriParsing = value; }
100 private static readonly string hexUpperChars = "0123456789ABCDEF";
101 private static readonly string [] Empty = new string [0];
102 private static bool isWin32 = (Path.DirectorySeparatorChar == '\\');
104 static readonly char[] hexUpperChars = new [] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
109 public static readonly string SchemeDelimiter = "://";
110 public static readonly string UriSchemeFile = "file";
111 public static readonly string UriSchemeFtp = "ftp";
112 public static readonly string UriSchemeGopher = "gopher";
113 public static readonly string UriSchemeHttp = "http";
114 public static readonly string UriSchemeHttps = "https";
115 public static readonly string UriSchemeMailto = "mailto";
116 public static readonly string UriSchemeNews = "news";
117 public static readonly string UriSchemeNntp = "nntp";
118 public static readonly string UriSchemeNetPipe = "net.pipe";
119 public static readonly string UriSchemeNetTcp = "net.tcp";
121 internal static readonly string UriSchemeTelnet = "telnet";
122 internal static readonly string UriSchemeLdap = "ldap";
123 internal static readonly string UriSchemeUuid = "uuid";
125 private static readonly string [] knownUriSchemes =
145 var iriparsingVar = Environment.GetEnvironmentVariable ("MONO_URI_IRIPARSING");
146 if (iriparsingVar == "true")
148 else if (iriparsingVar == "false")
152 public Uri (string uriString) : this (uriString, false)
156 protected Uri (SerializationInfo serializationInfo, StreamingContext streamingContext)
158 string uri = serializationInfo.GetString ("AbsoluteUri");
159 if (uri.Length > 0) {
161 ParseUri (UriKind.Absolute);
163 uri = serializationInfo.GetString ("RelativeUri");
164 if (uri.Length > 0) {
166 ParseUri (UriKind.Relative);
168 throw new ArgumentException ("Uri string was null or empty.");
173 public Uri (string uriString, UriKind uriKind)
179 case UriKind.Absolute:
181 throw new UriFormatException ("Invalid URI: The format of the URI could not be "
184 case UriKind.Relative:
186 throw new UriFormatException ("Invalid URI: The format of the URI could not be "
187 + "determined because the parameter 'uriString' represents an absolute URI.");
189 case UriKind.RelativeOrAbsolute:
192 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
193 throw new ArgumentException (msg);
198 // An exception-less constructor, returns success
199 // condition on the out parameter `success'.
201 Uri (string uriString, UriKind uriKind, out bool success)
203 if (uriString == null) {
208 if (uriKind != UriKind.RelativeOrAbsolute &&
209 uriKind != UriKind.Absolute &&
210 uriKind != UriKind.Relative) {
211 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
212 throw new ArgumentException (msg);
216 if (ParseNoExceptions (uriKind, uriString) != null)
222 case UriKind.Absolute:
226 case UriKind.Relative:
230 case UriKind.RelativeOrAbsolute:
239 public Uri (Uri baseUri, Uri relativeUri)
241 Merge (baseUri, relativeUri == null ? String.Empty : relativeUri.OriginalString);
242 // FIXME: this should call UriParser.Resolve
245 // note: doc says that dontEscape is always false but tests show otherwise
247 public Uri (string uriString, bool dontEscape)
249 userEscaped = dontEscape;
251 ParseUri (UriKind.Absolute);
253 throw new UriFormatException ("Invalid URI: The format of the URI could not be "
254 + "determined: " + uriString);
257 public Uri (Uri baseUri, string relativeUri)
259 Merge (baseUri, relativeUri);
260 // FIXME: this should call UriParser.Resolve
263 [Obsolete ("dontEscape is always false")]
264 public Uri (Uri baseUri, string relativeUri, bool dontEscape)
266 userEscaped = dontEscape;
267 Merge (baseUri, relativeUri);
270 private void Merge (Uri baseUri, string relativeUri)
273 throw new ArgumentNullException ("baseUri");
274 if (!baseUri.IsAbsoluteUri)
275 throw new ArgumentOutOfRangeException ("baseUri");
276 if (string.IsNullOrEmpty (relativeUri)) {
277 source = baseUri.OriginalString;
278 ParseUri (UriKind.Absolute);
283 bool startsWithSlash = false;
286 if (!UriParseComponents.TryParseComponents (baseUri.OriginalString, UriKind.Absolute, out baseEl, out error))
287 throw new UriFormatException (error);
289 if (relativeUri.StartsWith (baseEl.scheme + ":", StringComparison.Ordinal))
290 relativeUri = relativeUri.Substring (baseEl.scheme.Length + 1);
292 if (relativeUri.Length >= 1 && relativeUri [0] == '/') {
293 if (relativeUri.Length >= 2 && relativeUri [1] == '/') {
294 source = baseEl.scheme + ":" + relativeUri;
295 ParseUri (UriKind.Absolute);
299 relativeUri = relativeUri.Substring (1);
300 startsWithSlash = true;
303 UriElements relativeEl;
304 if (!UriParseComponents.TryParseComponents (relativeUri, UriKind.RelativeOrAbsolute, out relativeEl, out error))
305 throw new UriFormatException (error);
307 if (relativeEl.isAbsoluteUri) {
308 source = relativeUri;
309 ParseUri (UriKind.Absolute);
313 source = baseEl.scheme + baseEl.delimiter;
315 if (baseEl.user != null)
316 source += baseEl.user + "@";
318 source += baseEl.host;
320 if (baseEl.port >= 0)
321 source += ":" + baseEl.port.ToString (CultureInfo.InvariantCulture);
323 var canUseBase = true;
326 if (!string.IsNullOrEmpty (relativeEl.path) || startsWithSlash) {
328 path = relativeEl.path;
330 path = relativeEl.path;
332 var pathEnd = baseEl.path.LastIndexOf ('/');
333 path = (pathEnd > 0)? baseEl.path.Substring (0, pathEnd+1) : "";
334 path += relativeEl.path;
340 if ((path.Length == 0 || path [0] != '/') && baseEl.delimiter == SchemeDelimiter)
343 source += UriHelper.Reduce (path, true);
345 if (relativeEl.query != null) {
347 source += "?" + relativeEl.query;
348 } else if (canUseBase && baseEl.query != null)
349 source += "?" + baseEl.query;
351 if (relativeEl.fragment != null)
352 source += "#" + relativeEl.fragment;
353 else if (canUseBase && baseEl.fragment != null)
354 source += "#" + baseEl.fragment;
356 ParseUri (UriKind.Absolute);
363 public string AbsolutePath {
365 EnsureAbsoluteUri ();
366 if (scheme == "mailto" || scheme == "file")
367 // faster (mailto) and special (file) cases
370 if (path.Length == 0) {
371 string start = scheme + SchemeDelimiter;
372 if (path.StartsWith (start, StringComparison.Ordinal))
381 public string AbsoluteUri {
383 EnsureAbsoluteUri ();
385 if (cachedAbsoluteUri == null)
386 cachedAbsoluteUri = GetComponents (UriComponents.AbsoluteUri, UriFormat.UriEscaped);
388 return cachedAbsoluteUri;
392 public string Authority {
394 EnsureAbsoluteUri ();
395 return (GetDefaultPort (Scheme) == port)
396 ? host : host + ":" + port;
400 public string Fragment {
402 EnsureAbsoluteUri ();
409 EnsureAbsoluteUri ();
414 public UriHostNameType HostNameType {
416 EnsureAbsoluteUri ();
417 UriHostNameType ret = CheckHostName (Host);
418 if (ret != UriHostNameType.Unknown)
421 if (scheme == "mailto")
422 return UriHostNameType.Basic;
423 return (IsFile) ? UriHostNameType.Basic : ret;
427 public bool IsDefaultPort {
429 EnsureAbsoluteUri ();
430 return GetDefaultPort (Scheme) == port;
436 EnsureAbsoluteUri ();
437 return (Scheme == UriSchemeFile);
441 public bool IsLoopback {
443 EnsureAbsoluteUri ();
445 if (Host.Length == 0) {
449 if (host == "loopback" || host == "localhost")
453 if (IPAddress.TryParse (host, out result))
454 if (IPAddress.Loopback.Equals (result))
458 if (IPv6Address.TryParse (host, out result6)){
459 if (IPv6Address.IsLoopback (result6))
468 // rule: This should be true only if
469 // - uri string starts from "\\", or
470 // - uri string starts from "//" (Samba way)
472 EnsureAbsoluteUri ();
477 private bool IsLocalIdenticalToAbsolutePath ()
482 if ((scheme == Uri.UriSchemeNews) || (scheme == Uri.UriSchemeNntp) || (scheme == Uri.UriSchemeFtp))
485 return IsWellFormedOriginalString ();
488 public string LocalPath {
490 EnsureAbsoluteUri ();
491 if (cachedLocalPath != null)
492 return cachedLocalPath;
494 var formatFlags = UriHelper.FormatFlags.NoSlashReplace;
497 formatFlags |= UriHelper.FormatFlags.UserEscaped;
499 string unescapedPath = UriHelper.FormatAbsolute (path, scheme,
500 UriComponents.Path, UriFormat.Unescaped, formatFlags);
502 if (path.StartsWith ("/", StringComparison.Ordinal) &&
503 !unescapedPath.StartsWith ("/", StringComparison.Ordinal))
504 unescapedPath = "/" + unescapedPath;
506 if (IsLocalIdenticalToAbsolutePath ()) {
507 cachedLocalPath = unescapedPath;
508 return cachedLocalPath;
512 bool windows = (path.Length > 3 && path [1] == ':' &&
513 (path [2] == '\\' || path [2] == '/'));
516 cachedLocalPath = unescapedPath.Replace ('/', '\\');
518 cachedLocalPath = unescapedPath;
520 // support *nix and W32 styles
521 if (path.Length > 1 && path [1] == ':')
522 cachedLocalPath = unescapedPath.Replace (Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
524 // LAMESPEC: ok, now we cannot determine
525 // if such URI like "file://foo/bar" is
526 // Windows UNC or unix file path, so
527 // they should be handled differently.
528 else if (System.IO.Path.DirectorySeparatorChar == '\\') {
530 if (path.Length > 0) {
531 if ((path.Length > 1) || (path[0] != '/')) {
532 h += unescapedPath.Replace ('/', '\\');
535 cachedLocalPath = "\\\\" + h;
537 cachedLocalPath = unescapedPath;
539 if (cachedLocalPath.Length == 0)
540 cachedLocalPath = Path.DirectorySeparatorChar.ToString ();
541 return cachedLocalPath;
545 public string PathAndQuery {
547 EnsureAbsoluteUri ();
554 EnsureAbsoluteUri ();
559 public string Query {
561 EnsureAbsoluteUri ();
566 public string Scheme {
568 EnsureAbsoluteUri ();
573 public string [] Segments {
575 EnsureAbsoluteUri ();
577 // return a (pre-allocated) empty array
578 if (path.Length == 0)
582 return EmptyArray<string>.Value;
584 // do not return the original array (since items can be changed)
585 if (segments != null)
586 return segments.ToArray ();
588 List<string> list = new List<string> ();
589 StringBuilder current = new StringBuilder ();
590 for (int i = 0; i < path.Length; i++) {
594 current.Append (path [i]);
595 list.Add (current.ToString ());
599 if ((i < path.Length - 2) && (path [i + 1] == '5' && path [i + 2] == 'C')) {
600 current.Append ("%5C");
601 list.Add (current.ToString ());
605 current.Append ('%');
609 current.Append (path [i]);
614 if (current.Length > 0)
615 list.Add (current.ToString ());
617 if (IsFile && (list.Count > 0)) {
618 string first = list [0];
619 if ((first.Length > 1) && (first [1] == ':')) {
620 list.Insert (0, "/");
624 return segments.ToArray ();
628 public bool UserEscaped {
629 get { return userEscaped; }
632 public string UserInfo {
634 EnsureAbsoluteUri ();
635 return userinfo == null ? String.Empty : userinfo;
639 public string DnsSafeHost {
641 EnsureAbsoluteUri ();
643 if (HostNameType == UriHostNameType.IPv6) {
644 host = Host.Substring (1, Host.Length - 2);
646 host += "%" + scope_id.ToString ();
648 return Unescape (host);
652 public bool IsAbsoluteUri {
653 get { return isAbsoluteUri; }
656 public string OriginalString {
657 get { return source; }
662 public static UriHostNameType CheckHostName (string name)
664 if (name == null || name.Length == 0)
665 return UriHostNameType.Unknown;
667 if (IsIPv4Address (name))
668 return UriHostNameType.IPv4;
670 if (IsDomainAddress (name))
671 return UriHostNameType.Dns;
674 if (IPv6Address.TryParse (name, out addr))
675 return UriHostNameType.IPv6;
677 return UriHostNameType.Unknown;
680 internal static bool IsIPv4Address (string name)
682 string [] captures = name.Split (new char [] {'.'});
683 if (captures.Length != 4)
686 for (int i = 0; i < 4; i++) {
689 length = captures [i].Length;
693 if (!UInt32.TryParse (captures [i], out number))
701 internal static bool IsDomainAddress (string name)
703 int len = name.Length;
706 for (int i = 0; i < len; i++) {
709 if (!Char.IsLetterOrDigit (c))
711 } else if (c == '.') {
712 // www..host.com is bad
713 if (i + 1 < len && name [i + 1] == '.')
717 } else if (!Char.IsLetterOrDigit (c) && c != '-' && c != '_') {
728 [Obsolete ("This method does nothing, it has been obsoleted")]
729 protected virtual void Canonicalize ()
732 // This is flagged in the Microsoft documentation as used
733 // internally, no longer in use, and Obsolete.
737 [MonoTODO ("Find out what this should do")]
739 protected virtual void CheckSecurity ()
745 // defined in RFC3986 as = ALPHA *( ALPHA / DIGIT / "+" / "-" / ".")
746 public static bool CheckSchemeName (string schemeName)
748 if (schemeName == null || schemeName.Length == 0)
751 if (!IsAlpha (schemeName [0]))
754 int len = schemeName.Length;
755 for (int i = 1; i < len; i++) {
756 char c = schemeName [i];
757 if (!Char.IsDigit (c) && !IsAlpha (c) && c != '.' && c != '+' && c != '-')
764 private static bool IsAlpha (char c)
766 // as defined in rfc2234
767 // %x41-5A / %x61-7A (A-Z / a-z)
769 return (((i >= 0x41) && (i <= 0x5A)) || ((i >= 0x61) && (i <= 0x7A)));
772 public override bool Equals (object comparand)
774 if (comparand == null)
777 Uri uri = comparand as Uri;
778 if ((object) uri == null) {
779 string s = comparand as String;
783 if (!TryCreate (s, UriKind.RelativeOrAbsolute, out uri))
787 return InternalEquals (uri);
790 // Assumes: uri != null
791 bool InternalEquals (Uri uri)
793 if (this.isAbsoluteUri != uri.isAbsoluteUri)
795 if (!this.isAbsoluteUri)
796 return this.source == uri.source;
798 CultureInfo inv = CultureInfo.InvariantCulture;
799 return this.scheme.ToLower (inv) == uri.scheme.ToLower (inv)
800 && this.host.ToLower (inv) == uri.host.ToLower (inv)
801 && this.port == uri.port
802 && this.query == uri.query
803 && this.path == uri.path;
806 public static bool operator == (Uri uri1, Uri uri2)
808 return object.Equals (uri1, uri2);
811 public static bool operator != (Uri uri1, Uri uri2)
813 return !(uri1 == uri2);
816 public override int GetHashCode ()
818 if (cachedHashCode == 0) {
819 CultureInfo inv = CultureInfo.InvariantCulture;
821 cachedHashCode = scheme.ToLower (inv).GetHashCode ()
822 ^ host.ToLower (inv).GetHashCode ()
824 ^ query.GetHashCode ()
825 ^ path.GetHashCode ();
828 cachedHashCode = source.GetHashCode ();
831 return cachedHashCode;
834 public string GetLeftPart (UriPartial part)
836 EnsureAbsoluteUri ();
839 case UriPartial.Scheme :
840 return scheme + GetOpaqueWiseSchemeDelimiter ();
841 case UriPartial.Authority :
842 if ((scheme == Uri.UriSchemeMailto) || (scheme == Uri.UriSchemeNews))
845 StringBuilder s = new StringBuilder ();
847 s.Append (GetOpaqueWiseSchemeDelimiter ());
848 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
849 s.Append ('/'); // win32 file
850 if (userinfo != null)
851 s.Append (userinfo).Append ('@');
853 defaultPort = GetDefaultPort (scheme);
854 if ((port != -1) && (port != defaultPort))
855 s.Append (':').Append (port);
856 return s.ToString ();
857 case UriPartial.Path :
858 StringBuilder sb = new StringBuilder ();
860 sb.Append (GetOpaqueWiseSchemeDelimiter ());
861 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
862 sb.Append ('/'); // win32 file
863 if (userinfo != null)
864 sb.Append (userinfo).Append ('@');
866 defaultPort = GetDefaultPort (scheme);
867 if ((port != -1) && (port != defaultPort))
868 sb.Append (':').Append (port);
870 if (path.Length > 0) {
871 if (scheme == "mailto" || scheme == "news")
874 sb.Append (Reduce (path, CompactEscaped (scheme)));
876 return sb.ToString ();
881 public static int FromHex (char digit)
883 if ('0' <= digit && digit <= '9') {
884 return (int) (digit - '0');
887 if ('a' <= digit && digit <= 'f')
888 return (int) (digit - 'a' + 10);
890 if ('A' <= digit && digit <= 'F')
891 return (int) (digit - 'A' + 10);
893 throw new ArgumentException ("digit");
896 public static string HexEscape (char character)
898 if (character > 255) {
899 throw new ArgumentOutOfRangeException ("character");
902 return "%" + hexUpperChars [((character & 0xf0) >> 4)]
903 + hexUpperChars [((character & 0x0f))];
906 public static char HexUnescape (string pattern, ref int index)
909 throw new ArgumentException ("pattern");
911 if (index < 0 || index >= pattern.Length)
912 throw new ArgumentOutOfRangeException ("index");
914 if (!IsHexEncoding (pattern, index))
915 return pattern [index++];
918 int msb = FromHex (pattern [index++]);
919 int lsb = FromHex (pattern [index++]);
920 return (char) ((msb << 4) | lsb);
923 public static bool IsHexDigit (char character)
925 return (('0' <= character && character <= '9') ||
926 ('a' <= character && character <= 'f') ||
927 ('A' <= character && character <= 'F'));
930 public static bool IsHexEncoding (string pattern, int index)
932 if ((index + 3) > pattern.Length)
935 return ((pattern [index++] == '%') &&
936 IsHexDigit (pattern [index++]) &&
937 IsHexDigit (pattern [index]));
941 // Implemented by copying most of the MakeRelative code
943 public Uri MakeRelativeUri (Uri uri)
946 throw new ArgumentNullException ("uri");
947 if (Host != uri.Host || Scheme != uri.Scheme)
950 string result = String.Empty;
951 if (this.path != uri.path){
952 string [] segments = this.Segments;
953 string [] segments2 = uri.Segments;
956 int max = Math.Min (segments.Length, segments2.Length);
958 if (segments [k] != segments2 [k])
961 for (int i = k; i < segments.Length && segments [i].EndsWith ("/", StringComparison.Ordinal); i++)
963 for (int i = k; i < segments2.Length; i++)
964 result += segments2 [i];
966 if (result == string.Empty)
969 uri.AppendQueryAndFragment (ref result);
971 return new Uri (result, UriKind.Relative);
974 [Obsolete ("Use MakeRelativeUri(Uri uri) instead.")]
975 public string MakeRelative (Uri toUri)
977 if ((this.Scheme != toUri.Scheme) ||
978 (this.Authority != toUri.Authority))
979 return toUri.ToString ();
981 string result = String.Empty;
982 if (this.path != toUri.path){
983 string [] segments = this.Segments;
984 string [] segments2 = toUri.Segments;
986 int max = Math.Min (segments.Length, segments2.Length);
988 if (segments [k] != segments2 [k])
991 for (int i = k + 1; i < segments.Length; i++)
993 for (int i = k; i < segments2.Length; i++)
994 result += segments2 [i];
997 // Important: MakeRelative does not append fragment or query.
1002 void AppendQueryAndFragment (ref string result)
1004 if (query.Length > 0) {
1005 string q = query [0] == '?' ? '?' + Unescape (query.Substring (1), true, false) : Unescape (query, false);
1008 if (fragment.Length > 0)
1009 result += Unescape (fragment, true, false);
1012 public override string ToString ()
1014 if (cachedToString != null)
1015 return cachedToString;
1017 if (isAbsoluteUri) {
1018 if (Parser is DefaultUriParser)
1019 cachedToString = Parser.GetComponentsHelper (this, UriComponents.AbsoluteUri, UriHelper.ToStringUnescape);
1021 cachedToString = Parser.GetComponents (this, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped);
1023 cachedToString = UriHelper.FormatRelative (source, scheme, UriHelper.ToStringUnescape);
1025 return cachedToString;
1028 protected void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
1030 if (this.isAbsoluteUri) {
1031 serializationInfo.AddValue ("AbsoluteUri", this.AbsoluteUri);
1033 serializationInfo.AddValue ("AbsoluteUri", String.Empty);
1034 serializationInfo.AddValue ("RelativeUri", this.OriginalString);
1038 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
1040 GetObjectData (info, context);
1047 protected virtual void Escape ()
1049 path = EscapeString (path);
1053 protected static string EscapeString (string str)
1055 return EscapeString (str, Uri.EscapeCommonHexBrackets);
1058 private const string EscapeCommon = "<>%\"{}|\\^`";
1059 private const string EscapeReserved = ";/?:@&=+$,";
1060 private const string EscapeFragment = "#";
1061 private const string EscapeBrackets = "[]";
1063 private const string EscapeNews = EscapeCommon + EscapeBrackets + "?";
1064 private const string EscapeCommonHex = EscapeCommon + EscapeFragment;
1065 private const string EscapeCommonBrackets = EscapeCommon + EscapeBrackets;
1066 internal const string EscapeCommonHexBrackets = EscapeCommon + EscapeFragment + EscapeBrackets;
1067 internal const string EscapeCommonHexBracketsQuery = EscapeCommonHexBrackets + "?";
1069 internal static string EscapeString (string str, string escape)
1071 return EscapeString (str, escape, true);
1074 internal static string EscapeString (string str, string escape, bool nonAsciiEscape)
1076 if (String.IsNullOrEmpty (str))
1077 return String.Empty;
1079 StringBuilder s = new StringBuilder ();
1080 int len = str.Length;
1081 for (int i = 0; i < len; i++) {
1082 // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
1083 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
1084 // control = <US-ASCII coded characters 00-1F and 7F hexadecimal>
1085 // space = <US-ASCII coded character 20 hexadecimal>
1086 // delims = "<" | ">" | "#" | "%" | <">
1087 // unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
1089 // check for escape code already placed in str,
1090 // i.e. for encoding that follows the pattern
1091 // "%hexhex" in a string, where "hex" is a digit from 0-9
1092 // or a letter from A-F (case-insensitive).
1093 if (IsHexEncoding (str,i)) {
1094 // if ,yes , copy it as is
1095 s.Append (str.Substring (i, 3));
1101 bool outside_limited_ascii = ((c <= 0x20) || (c >= 0x7f));
1102 bool needs_escape = (escape.IndexOf (c) != -1);
1103 if (nonAsciiEscape && outside_limited_ascii) {
1104 byte [] data = Encoding.UTF8.GetBytes (new char [] { c });
1105 int length = data.Length;
1106 for (int j = 0; j < length; j++) {
1107 c = (char) data [j];
1108 if (needs_escape || nonAsciiEscape)
1109 s.Append (HexEscape (c));
1113 } else if (needs_escape) {
1114 s.Append (HexEscape (c));
1120 return s.ToString ();
1123 // On .NET 1.x, this method is called from .ctor(). When overriden, we
1124 // can avoid the "absolute uri" constraints of the .ctor() by
1125 // overriding with custom code.
1126 [Obsolete("The method has been deprecated. It is not used by the system.")]
1127 protected virtual void Parse ()
1131 private void ParseUri (UriKind kind)
1133 Parse (kind, source);
1138 if (host.Length > 1 && host [0] != '[' && host [host.Length - 1] != ']') {
1139 // host name present (but not an IPv6 address)
1140 host = host.ToLower (CultureInfo.InvariantCulture);
1145 protected virtual string Unescape (string path)
1147 var formatFlags = UriHelper.FormatFlags.NoSlashReplace | UriHelper.FormatFlags.NoReduce;
1148 return UriHelper.FormatAbsolute (path, scheme, UriComponents.Path, UriFormat.Unescaped, formatFlags);
1151 internal static string Unescape (string str, bool excludeSpecial)
1153 return Unescape (str, excludeSpecial, excludeSpecial);
1156 internal static string Unescape (string str, bool excludeSpecial, bool excludeBackslash)
1158 if (String.IsNullOrEmpty (str))
1159 return String.Empty;
1161 StringBuilder s = new StringBuilder ();
1162 int len = str.Length;
1163 for (int i = 0; i < len; i++) {
1167 char x = HexUnescapeMultiByte (str, ref i, out surrogate);
1168 if (excludeSpecial && x == '#')
1170 else if (excludeSpecial && x == '%')
1172 else if (excludeSpecial && x == '?')
1174 else if (excludeBackslash && x == '\\')
1178 if (surrogate != char.MinValue)
1179 s.Append (surrogate);
1185 return s.ToString ();
1191 private void ParseAsWindowsUNC (string uriString)
1193 scheme = UriSchemeFile;
1195 fragment = String.Empty;
1196 query = String.Empty;
1199 uriString = uriString.TrimStart (new char [] {'\\'});
1200 int pos = uriString.IndexOf ('\\');
1202 path = uriString.Substring (pos);
1203 host = uriString.Substring (0, pos);
1204 } else { // "\\\\server"
1206 path = String.Empty;
1208 path = path.Replace ("\\", "/");
1212 // Returns null on success, string with error on failure
1214 private string ParseAsWindowsAbsoluteFilePath (string uriString)
1216 if (uriString.Length > 2 && uriString [2] != '\\' && uriString [2] != '/')
1217 return "Relative file path is not allowed.";
1218 scheme = UriSchemeFile;
1219 host = String.Empty;
1221 path = uriString.Replace ("\\", "/");
1222 fragment = String.Empty;
1223 query = String.Empty;
1228 private void ParseAsUnixAbsoluteFilePath (string uriString)
1230 scheme = UriSchemeFile;
1232 fragment = String.Empty;
1233 query = String.Empty;
1234 host = String.Empty;
1237 if (uriString.Length >= 2 && uriString [0] == '/' && uriString [1] == '/') {
1238 uriString = uriString.TrimStart (new char [] {'/'});
1239 // Now we don't regard //foo/bar as "foo" host.
1241 int pos = uriString.IndexOf ('/');
1243 path = '/' + uriString.Substring (pos + 1);
1244 host = uriString.Substring (0, pos);
1245 } else { // "///server"
1247 path = String.Empty;
1250 path = '/' + uriString;
1257 // This parse method will throw exceptions on failure
1259 private void Parse (UriKind kind, string uriString)
1261 if (uriString == null)
1262 throw new ArgumentNullException ("uriString");
1264 string s = ParseNoExceptions (kind, uriString);
1266 throw new UriFormatException (s);
1269 private bool SupportsQuery ()
1271 return UriHelper.SupportsQuery (scheme);
1275 private string ParseNoExceptions (UriKind kind, string uriString)
1277 UriElements elements;
1279 if (!UriParseComponents.TryParseComponents (source, kind, out elements, out error))
1282 scheme = elements.scheme;
1283 var parser = UriParser.GetParser (scheme);
1284 if (parser != null && !(parser is DefaultUriParser)) {
1285 userinfo = Parser.GetComponents (this, UriComponents.UserInfo, UriFormat.UriEscaped);
1286 host = Parser.GetComponents (this, UriComponents.Host, UriFormat.UriEscaped);
1288 var portStr = Parser.GetComponents (this, UriComponents.StrongPort, UriFormat.UriEscaped);
1289 if (!string.IsNullOrEmpty (portStr))
1290 port = int.Parse (portStr);
1292 path = Parser.GetComponents (this, UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.UriEscaped);
1293 query = Parser.GetComponents (this, UriComponents.Query, UriFormat.UriEscaped);
1294 fragment = Parser.GetComponents (this, UriComponents.StrongPort, UriFormat.UriEscaped);
1299 var formatFlags = UriHelper.FormatFlags.None;
1300 if (UriHelper.HasCharactersToNormalize (uriString))
1301 formatFlags |= UriHelper.FormatFlags.HasUriCharactersToNormalize;
1304 formatFlags |= UriHelper.FormatFlags.UserEscaped;
1306 if (elements.host != null)
1307 formatFlags |= UriHelper.FormatFlags.HasHost;
1309 userinfo = elements.user;
1311 if (elements.host != null) {
1312 host = UriHelper.FormatAbsolute (elements.host, scheme,
1313 UriComponents.Host, UriFormat.UriEscaped, formatFlags);
1316 port = elements.port;
1319 port = GetDefaultPort (scheme);
1321 if (elements.path != null) {
1322 path = UriHelper.FormatAbsolute (elements.path, scheme,
1323 UriComponents.Path, UriFormat.UriEscaped, formatFlags);
1324 if (elements.delimiter == SchemeDelimiter && string.IsNullOrEmpty (path))
1328 if (elements.query != null) {
1329 query = "?" + UriHelper.FormatAbsolute (elements.query, scheme,
1330 UriComponents.Query, UriFormat.UriEscaped, formatFlags);
1333 if (elements.fragment != null) {
1334 fragment = "#" + UriHelper.FormatAbsolute (elements.fragment, scheme,
1335 UriComponents.Fragment, UriFormat.UriEscaped, formatFlags);
1338 isAbsoluteUri = elements.isAbsoluteUri;
1339 isUnc = elements.isUnc;
1340 scope_id = elements.scopeId;
1345 private static string TryGetKnownUriSchemeInstance (string scheme)
1347 foreach (string knownScheme in knownUriSchemes) {
1348 if (knownScheme == scheme)
1355 private static bool CompactEscaped (string scheme)
1357 if (scheme == null || scheme.Length < 4)
1360 char first = scheme [0];
1362 return scheme == "http" || scheme == "https";
1363 } else if (first == 'f' && scheme == "file"){
1365 } else if (first == 'n')
1366 return scheme == "net.pipe" || scheme == "net.tcp";
1371 // replace '\', %5C ('\') and %2f ('/') into '/'
1372 // replace %2e ('.') into '.'
1373 private static string NormalizePath (string path)
1375 StringBuilder res = new StringBuilder ();
1376 for (int i = 0; i < path.Length; i++) {
1383 if (i < path.Length - 2) {
1384 char c1 = path [i + 1];
1385 char c2 = Char.ToUpper (path [i + 2]);
1386 if ((c1 == '2') && (c2 == 'E')) {
1389 } else if (((c1 == '2') && (c2 == 'F')) || ((c1 == '5') && (c2 == 'C'))) {
1398 return res.ToString ();
1401 // This is called "compacting" in the MSDN documentation
1402 private static string Reduce (string path, bool compact_escaped)
1404 // quick out, allocation-free, for a common case
1408 if (compact_escaped && (path.IndexOf ('%') != -1)) {
1409 // replace '\', %2f, %5c with '/' and replace %2e with '.'
1410 // other escaped values seems to survive this step
1411 path = NormalizePath (path);
1413 // (always) replace '\' with '/'
1414 path = path.Replace ('\\', '/');
1417 List<string> result = new List<string> ();
1420 for (int startpos = 0; startpos < path.Length; ) {
1421 int endpos = path.IndexOf ('/', startpos);
1423 endpos = path.Length;
1424 string current = path.Substring (startpos, endpos-startpos);
1425 startpos = endpos + 1;
1426 if ((begin && current.Length == 0) || current == "." ) {
1432 if (current == "..") {
1433 int resultCount = result.Count;
1434 // in 2.0 profile, skip leading ".." parts
1435 if (resultCount == 0) {
1439 result.RemoveAt (resultCount - 1);
1443 result.Add (current);
1446 if (result.Count == 0)
1449 StringBuilder res = new StringBuilder ();
1451 if (path [0] == '/')
1455 foreach (string part in result) {
1464 if (path [path.Length - 1] == '/')
1467 return res.ToString ();
1470 // A variant of HexUnescape() which can decode multi-byte escaped
1471 // sequences such as (e.g.) %E3%81%8B into a single character
1472 internal static char HexUnescapeMultiByte (string pattern, ref int index, out char surrogate)
1475 return HexUnescapeMultiByte (pattern, ref index, out surrogate, out invalidEscape);
1478 internal static char HexUnescapeMultiByte (string pattern, ref int index, out char surrogate, out bool invalidEscape)
1480 surrogate = char.MinValue;
1481 invalidEscape = false;
1483 if (pattern == null)
1484 throw new ArgumentException ("pattern");
1486 if (index < 0 || index >= pattern.Length)
1487 throw new ArgumentOutOfRangeException ("index");
1489 if (!IsHexEncoding (pattern, index))
1490 return pattern [index++];
1492 int orig_index = index++;
1493 int msb = FromHex (pattern [index++]);
1494 int lsb = FromHex (pattern [index++]);
1496 // We might be dealing with a multi-byte character:
1497 // The number of ones at the top-end of the first byte will tell us
1498 // how many bytes will make up this character.
1501 while ((msb_copy & 0x8) == 0x8) {
1506 // We might be dealing with a single-byte character:
1507 // If there was only 0 or 1 leading ones then we're not dealing
1508 // with a multi-byte character.
1509 if (num_bytes <= 1) {
1510 var c = (char) ((msb << 4) | lsb);
1511 invalidEscape = c > 0x7F;
1515 // Now that we know how many bytes *should* follow, we'll check them
1516 // to ensure we are dealing with a valid multi-byte character.
1517 byte [] chars = new byte [num_bytes];
1518 bool all_invalid = false;
1519 chars[0] = (byte) ((msb << 4) | lsb);
1521 for (int i = 1; i < num_bytes; i++) {
1522 if (!IsHexEncoding (pattern, index++)) {
1527 // All following bytes must be in the form 10xxxxxx
1528 int cur_msb = FromHex (pattern [index++]);
1529 if ((cur_msb & 0xc) != 0x8) {
1534 int cur_lsb = FromHex (pattern [index++]);
1535 chars[i] = (byte) ((cur_msb << 4) | cur_lsb);
1538 // If what looked like a multi-byte character is invalid, then we'll
1539 // just return the first byte as a single byte character.
1541 invalidEscape = true;
1542 index = orig_index + 3;
1543 return (char) chars[0];
1546 // Otherwise, we're dealing with a valid multi-byte character.
1547 // We need to ignore the leading ones from the first byte:
1548 byte mask = (byte) 0xFF;
1549 mask >>= (num_bytes + 1);
1550 int result = chars[0] & mask;
1552 // The result will now be built up from the following bytes.
1553 for (int i = 1; i < num_bytes; i++) {
1554 // Ignore upper two bits
1556 result |= (chars[i] & 0x3F);
1559 if (result <= 0xFFFF) {
1560 return (char) result;
1562 // We need to handle this as a UTF16 surrogate (i.e. return
1565 surrogate = (char) ((result & 0x3FF) | 0xDC00);
1566 return (char) ((result >> 10) | 0xD800);
1570 private struct UriScheme
1572 public string scheme;
1573 public string delimiter;
1574 public int defaultPort;
1576 public UriScheme (string s, string d, int p)
1584 static UriScheme [] schemes = new UriScheme [] {
1585 new UriScheme (UriSchemeHttp, SchemeDelimiter, 80),
1586 new UriScheme (UriSchemeHttps, SchemeDelimiter, 443),
1587 new UriScheme (UriSchemeFtp, SchemeDelimiter, 21),
1588 new UriScheme (UriSchemeFile, SchemeDelimiter, -1),
1589 new UriScheme (UriSchemeMailto, ":", 25),
1590 new UriScheme (UriSchemeNews, ":", 119),
1591 new UriScheme (UriSchemeUuid, ":", -1),
1592 new UriScheme (UriSchemeNntp, SchemeDelimiter, 119),
1593 new UriScheme (UriSchemeGopher, SchemeDelimiter, 70),
1596 internal static string GetSchemeDelimiter (string scheme)
1598 for (int i = 0; i < schemes.Length; i++)
1599 if (schemes [i].scheme == scheme)
1600 return schemes [i].delimiter;
1601 return Uri.SchemeDelimiter;
1604 internal static int GetDefaultPort (string scheme)
1606 UriParser parser = UriParser.GetParser (scheme);
1609 return parser.DefaultPort;
1612 private string GetOpaqueWiseSchemeDelimiter ()
1614 return GetSchemeDelimiter (scheme);
1618 protected virtual bool IsBadFileSystemCharacter (char character)
1620 // It does not always overlap with InvalidPathChars.
1621 int chInt = (int) character;
1622 if (chInt < 32 || (chInt < 64 && chInt > 57))
1641 protected static bool IsExcludedCharacter (char character)
1643 if (character <= 32 || character >= 127)
1646 if (character == '"' || character == '#' || character == '%' || character == '<' ||
1647 character == '>' || character == '[' || character == '\\' || character == ']' ||
1648 character == '^' || character == '`' || character == '{' || character == '|' ||
1654 internal static bool MaybeUri (string s)
1656 int p = s.IndexOf (':');
1663 return IsPredefinedScheme (s.Substring (0, p));
1667 // Using a simple block of if's is twice as slow as the compiler generated
1668 // switch statement. But using this tuned code is faster than the
1669 // compiler generated code, with a million loops on x86-64:
1671 // With "http": .10 vs .51 (first check)
1672 // with "https": .16 vs .51 (second check)
1673 // with "foo": .22 vs .31 (never found)
1674 // with "mailto": .12 vs .51 (last check)
1677 private static bool IsPredefinedScheme (string scheme)
1679 if (scheme == null || scheme.Length < 3)
1682 char c = scheme [0];
1684 return (scheme == "http" || scheme == "https");
1686 return (scheme == "file" || scheme == "ftp");
1691 return (scheme == "news" || scheme == "net.pipe" || scheme == "net.tcp");
1692 if (scheme == "nntp")
1696 if ((c == 'g' && scheme == "gopher") || (c == 'm' && scheme == "mailto"))
1703 protected virtual bool IsReservedCharacter (char character)
1705 if (character == '$' || character == '&' || character == '+' || character == ',' ||
1706 character == '/' || character == ':' || character == ';' || character == '=' ||
1713 private UriParser parser;
1715 private UriParser Parser {
1717 if (parser == null) {
1718 parser = UriParser.GetParser (scheme);
1719 // no specific parser ? then use a default one
1721 parser = new DefaultUriParser ("*");
1725 set { parser = value; }
1728 public string GetComponents (UriComponents components, UriFormat format)
1730 if ((components & UriComponents.SerializationInfoString) == 0)
1731 EnsureAbsoluteUri ();
1733 return Parser.GetComponents (this, components, format);
1736 public bool IsBaseOf (Uri uri)
1739 throw new ArgumentNullException ("uri");
1740 return Parser.IsBaseOf (this, uri);
1743 public bool IsWellFormedOriginalString ()
1745 // funny, but it does not use the Parser's IsWellFormedOriginalString().
1746 // Also, it seems we need to *not* escape hex.
1747 return EscapeString (OriginalString, EscapeCommonBrackets) == OriginalString;
1752 private const int MaxUriLength = 32766;
1754 public static int Compare (Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType)
1756 if ((comparisonType < StringComparison.CurrentCulture) || (comparisonType > StringComparison.OrdinalIgnoreCase)) {
1757 string msg = Locale.GetText ("Invalid StringComparison value '{0}'", comparisonType);
1758 throw new ArgumentException ("comparisonType", msg);
1761 if ((uri1 == null) && (uri2 == null))
1768 string s1 = uri1.GetComponents (partsToCompare, compareFormat);
1769 string s2 = uri2.GetComponents (partsToCompare, compareFormat);
1770 return String.Compare (s1, s2, comparisonType);
1774 // The rules for EscapeDataString
1776 static bool NeedToEscapeDataChar (char b)
1778 if ((b >= 'A' && b <= 'Z') ||
1779 (b >= 'a' && b <= 'z') ||
1780 (b >= '0' && b <= '9'))
1795 public static string EscapeDataString (string stringToEscape)
1797 if (stringToEscape == null)
1798 throw new ArgumentNullException ("stringToEscape");
1800 if (stringToEscape.Length > MaxUriLength) {
1801 throw new UriFormatException (string.Format ("Uri is longer than the maximum {0} characters.", MaxUriLength));
1804 bool escape = false;
1805 foreach (char c in stringToEscape){
1806 if (NeedToEscapeDataChar (c)){
1812 return stringToEscape;
1815 StringBuilder sb = new StringBuilder ();
1816 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
1817 foreach (byte b in bytes){
1818 if (NeedToEscapeDataChar ((char) b))
1819 sb.Append (HexEscape ((char) b));
1821 sb.Append ((char) b);
1823 return sb.ToString ();
1827 // The rules for EscapeUriString
1829 static bool NeedToEscapeUriChar (char b)
1831 if ((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '&' && b <= ';'))
1852 public static string EscapeUriString (string stringToEscape)
1854 if (stringToEscape == null)
1855 throw new ArgumentNullException ("stringToEscape");
1857 if (stringToEscape.Length > MaxUriLength) {
1858 throw new UriFormatException (string.Format ("Uri is longer than the maximum {0} characters.", MaxUriLength));
1861 bool escape = false;
1862 foreach (char c in stringToEscape){
1863 if (NeedToEscapeUriChar (c)){
1869 return stringToEscape;
1871 StringBuilder sb = new StringBuilder ();
1872 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
1873 foreach (byte b in bytes){
1874 if (NeedToEscapeUriChar ((char) b))
1875 sb.Append (HexEscape ((char) b));
1877 sb.Append ((char) b);
1879 return sb.ToString ();
1882 public static bool IsWellFormedUriString (string uriString, UriKind uriKind)
1884 if (uriString == null)
1888 if (Uri.TryCreate (uriString, uriKind, out uri))
1889 return uri.IsWellFormedOriginalString ();
1893 public static bool TryCreate (string uriString, UriKind uriKind, out Uri result)
1897 Uri r = new Uri (uriString, uriKind, out success);
1906 // [MonoTODO ("rework code to avoid exception catching")]
1907 public static bool TryCreate (Uri baseUri, string relativeUri, out Uri result)
1910 if (relativeUri == null)
1914 Uri relative = new Uri (relativeUri, UriKind.RelativeOrAbsolute);
1915 if ((baseUri != null) && baseUri.IsAbsoluteUri) {
1916 // FIXME: this should call UriParser.Resolve
1917 result = new Uri (baseUri, relative);
1918 } else if (relative.IsAbsoluteUri) {
1919 // special case - see unit tests
1922 return (result != null);
1923 } catch (UriFormatException) {
1928 //[MonoTODO ("rework code to avoid exception catching")]
1929 public static bool TryCreate (Uri baseUri, Uri relativeUri, out Uri result)
1932 if ((baseUri == null) || !baseUri.IsAbsoluteUri)
1934 if (relativeUri == null)
1937 // FIXME: this should call UriParser.Resolve
1938 result = new Uri (baseUri, relativeUri.OriginalString);
1940 } catch (UriFormatException) {
1945 public static string UnescapeDataString (string stringToUnescape)
1947 return UnescapeDataString (stringToUnescape, false);
1950 internal static string UnescapeDataString (string stringToUnescape, bool safe)
1952 if (stringToUnescape == null)
1953 throw new ArgumentNullException ("stringToUnescape");
1955 if (stringToUnescape.IndexOf ('%') == -1 && stringToUnescape.IndexOf ('+') == -1)
1956 return stringToUnescape;
1958 StringBuilder output = new StringBuilder ();
1959 long len = stringToUnescape.Length;
1960 MemoryStream bytes = new MemoryStream ();
1963 for (int i = 0; i < len; i++) {
1964 if (stringToUnescape [i] == '%' && i + 2 < len && stringToUnescape [i + 1] != '%') {
1965 if (stringToUnescape [i + 1] == 'u' && i + 5 < len) {
1966 if (bytes.Length > 0) {
1967 output.Append (GetChars (bytes, Encoding.UTF8));
1968 bytes.SetLength (0);
1971 xchar = GetChar (stringToUnescape, i + 2, 4, safe);
1973 output.Append ((char) xchar);
1977 output.Append ('%');
1980 else if ((xchar = GetChar (stringToUnescape, i + 1, 2, safe)) != -1) {
1981 bytes.WriteByte ((byte) xchar);
1985 output.Append ('%');
1990 if (bytes.Length > 0) {
1991 output.Append (GetChars (bytes, Encoding.UTF8));
1992 bytes.SetLength (0);
1995 output.Append (stringToUnescape [i]);
1998 if (bytes.Length > 0) {
1999 output.Append (GetChars (bytes, Encoding.UTF8));
2003 return output.ToString ();
2006 private static int GetInt (byte b)
2009 if (c >= '0' && c <= '9')
2012 if (c >= 'a' && c <= 'f')
2013 return c - 'a' + 10;
2015 if (c >= 'A' && c <= 'F')
2016 return c - 'A' + 10;
2021 private static int GetChar (string str, int offset, int length, bool safe)
2024 int end = length + offset;
2025 for (int i = offset; i < end; i++) {
2030 int current = GetInt ((byte) c);
2033 val = (val << 4) + current;
2039 switch ((char) val) {
2046 case '&': // not documented
2053 private static char [] GetChars (MemoryStream b, Encoding e)
2055 return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
2059 private void EnsureAbsoluteUri ()
2062 throw new InvalidOperationException ("This operation is not supported for a relative URI.");