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.Globalization;
51 // Disable warnings on Obsolete methods being used
53 #pragma warning disable 612
58 [TypeConverter (typeof (UriTypeConverter))]
59 public class Uri : ISerializable {
61 // o scheme excludes the scheme delimiter
62 // o port is -1 to indicate no port is defined
63 // o path is empty or starts with / when scheme delimiter == "://"
64 // o query is empty or starts with ? char, escaped.
65 // o fragment is empty or starts with # char, unescaped.
66 // o all class variables are in escaped format when they are escapable,
67 // except cachedToString.
68 // o UNC is supported, as starts with "\\" for windows,
71 private bool isUnixFilePath;
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 = String.Empty;
81 private bool isOpaquePart;
82 private bool isAbsoluteUri = true;
84 private 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 readonly string hexUpperChars = "0123456789ABCDEF";
96 public static readonly string SchemeDelimiter = "://";
97 public static readonly string UriSchemeFile = "file";
98 public static readonly string UriSchemeFtp = "ftp";
99 public static readonly string UriSchemeGopher = "gopher";
100 public static readonly string UriSchemeHttp = "http";
101 public static readonly string UriSchemeHttps = "https";
102 public static readonly string UriSchemeMailto = "mailto";
103 public static readonly string UriSchemeNews = "news";
104 public static readonly string UriSchemeNntp = "nntp";
105 public static readonly string UriSchemeNetPipe = "net.pipe";
106 public static readonly string UriSchemeNetTcp = "net.tcp";
111 public Uri (string uriString) : this (uriString, UriKind.Absolute)
115 public Uri (string uriString) : this (uriString, false)
119 protected Uri (SerializationInfo serializationInfo, StreamingContext streamingContext)
121 string uri = serializationInfo.GetString ("AbsoluteUri");
122 if (uri.Length > 0) {
124 ParseUri(UriKind.Absolute);
126 uri = serializationInfo.GetString ("RelativeUri");
127 if (uri.Length > 0) {
129 ParseUri(UriKind.Relative);
131 throw new ArgumentException("Uri string was null or empty.");
136 public Uri (string uriString, UriKind uriKind)
142 case UriKind.Absolute:
144 throw new UriFormatException("Invalid URI: The format of the URI could not be "
147 case UriKind.Relative:
149 throw new UriFormatException("Invalid URI: The format of the URI could not be "
150 + "determined because the parameter 'uriString' represents an absolute URI.");
152 case UriKind.RelativeOrAbsolute:
155 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
156 throw new ArgumentException (msg);
161 // An exception-less constructor, returns success
162 // condition on the out parameter `success'.
164 Uri (string uriString, UriKind uriKind, out bool success)
166 if (uriString == null) {
171 if (uriKind != UriKind.RelativeOrAbsolute &&
172 uriKind != UriKind.Absolute &&
173 uriKind != UriKind.Relative) {
174 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
175 throw new ArgumentException (msg);
179 if (ParseNoExceptions (uriKind, uriString) != null)
185 case UriKind.Absolute:
189 case UriKind.Relative:
193 case UriKind.RelativeOrAbsolute:
202 public Uri (Uri baseUri, Uri relativeUri)
204 Merge (baseUri, relativeUri == null ? String.Empty : relativeUri.OriginalString);
205 // FIXME: this should call UriParser.Resolve
208 // note: doc says that dontEscape is always false but tests show otherwise
210 public Uri (string uriString, bool dontEscape)
212 userEscaped = dontEscape;
214 ParseUri (UriKind.Absolute);
216 throw new UriFormatException("Invalid URI: The format of the URI could not be "
217 + "determined: " + uriString);
220 public Uri (Uri baseUri, string relativeUri)
222 Merge (baseUri, relativeUri);
223 // FIXME: this should call UriParser.Resolve
226 [Obsolete ("dontEscape is always false")]
227 public Uri (Uri baseUri, string relativeUri, bool dontEscape)
229 userEscaped = dontEscape;
230 Merge (baseUri, relativeUri);
233 private void Merge (Uri baseUri, string relativeUri)
236 throw new ArgumentNullException ("baseUri");
237 if (!baseUri.IsAbsoluteUri)
238 throw new ArgumentOutOfRangeException ("baseUri");
239 if (relativeUri == null)
240 relativeUri = String.Empty;
242 // See RFC 2396 Par 5.2 and Appendix C
244 // Check Windows UNC (for // it is scheme/host separator)
245 if (relativeUri.Length >= 2 && relativeUri [0] == '\\' && relativeUri [1] == '\\') {
246 source = relativeUri;
247 ParseUri (UriKind.Absolute);
251 int pos = relativeUri.IndexOf (':');
254 int pos2 = relativeUri.IndexOfAny (new char [] {'/', '\\', '?'});
256 // pos2 < 0 ... e.g. mailto
257 // pos2 > pos ... to block ':' in query part
258 if (pos2 > pos || pos2 < 0) {
259 // in some cases, it is equivanent to new Uri (relativeUri, dontEscape):
260 // 1) when the URI scheme in the
261 // relative path is different from that
262 // of the baseUri, or
263 // 2) the URI scheme is non-standard
264 // ones (non-standard URIs are always
265 // treated as absolute here), or
266 // 3) the relative URI path is absolute.
267 if (String.CompareOrdinal (baseUri.Scheme, 0, relativeUri, 0, pos) != 0 ||
268 !IsPredefinedScheme (baseUri.Scheme) ||
269 relativeUri.Length > pos + 1 &&
270 relativeUri [pos + 1] == '/') {
271 source = relativeUri;
272 ParseUri (UriKind.Absolute);
276 relativeUri = relativeUri.Substring (pos + 1);
280 this.scheme = baseUri.scheme;
281 this.host = baseUri.host;
282 this.port = baseUri.port;
283 this.userinfo = baseUri.userinfo;
284 this.isUnc = baseUri.isUnc;
285 this.isUnixFilePath = baseUri.isUnixFilePath;
286 this.isOpaquePart = baseUri.isOpaquePart;
288 if (relativeUri == String.Empty) {
289 this.path = baseUri.path;
290 this.query = baseUri.query;
291 this.fragment = baseUri.fragment;
296 // Note that in relative constructor, file URI cannot handle '#' as a filename character, but just regarded as a fragment identifier.
297 pos = relativeUri.IndexOf ('#');
300 fragment = relativeUri.Substring (pos);
302 fragment = "#" + EscapeString (relativeUri.Substring (pos+1));
303 relativeUri = relativeUri.Substring (0, pos);
307 pos = relativeUri.IndexOf ('?');
309 query = relativeUri.Substring (pos);
311 query = EscapeString (query);
312 relativeUri = relativeUri.Substring (0, pos);
315 if (relativeUri.Length > 0 && relativeUri [0] == '/') {
316 if (relativeUri.Length > 1 && relativeUri [1] == '/') {
317 source = scheme + ':' + relativeUri;
318 ParseUri (UriKind.Absolute);
323 path = EscapeString (path);
331 if (relativeUri.Length > 0) {
333 if (relativeUri.Length > 0 || query.Length > 0) {
335 pos = path.LastIndexOf ('/');
337 path = path.Substring (0, pos + 1);
340 if(relativeUri.Length == 0)
349 pos = path.IndexOf ("./", startIndex);
353 path = path.Remove (0, 2);
354 else if (path [pos - 1] != '.')
355 path = path.Remove (pos, 2);
357 startIndex = pos + 1;
361 if (path.Length > 1 &&
362 path [path.Length - 1] == '.' &&
363 path [path.Length - 2] == '/')
364 path = path.Remove (path.Length - 1, 1);
369 pos = path.IndexOf ("/../", startIndex);
376 int pos2 = path.LastIndexOf ('/', pos - 1);
378 startIndex = pos + 1;
380 if (path.Substring (pos2 + 1, pos - pos2 - 1) != "..")
381 path = path.Remove (pos2 + 1, pos - pos2 + 3);
383 startIndex = pos + 1;
388 if (path.Length > 3 && path.EndsWith ("/..")) {
389 pos = path.LastIndexOf ('/', path.Length - 4);
391 if (path.Substring (pos + 1, path.Length - pos - 4) != "..")
392 path = path.Remove (pos + 1, path.Length - pos - 1);
396 path = EscapeString (path);
401 public string AbsolutePath {
403 EnsureAbsoluteUri ();
407 // faster (mailto) and special (file) cases
410 if (path.Length == 0) {
411 string start = Scheme + SchemeDelimiter;
412 if (path.StartsWith (start))
422 public string AbsoluteUri {
424 EnsureAbsoluteUri ();
425 if (cachedAbsoluteUri == null) {
426 cachedAbsoluteUri = GetLeftPart (UriPartial.Path);
427 if (query.Length > 0)
428 cachedAbsoluteUri += query;
429 if (fragment.Length > 0)
430 cachedAbsoluteUri += fragment;
432 return cachedAbsoluteUri;
436 public string Authority {
438 EnsureAbsoluteUri ();
439 return (GetDefaultPort (Scheme) == port)
440 ? host : host + ":" + port;
444 public string Fragment {
446 EnsureAbsoluteUri ();
453 EnsureAbsoluteUri ();
458 public UriHostNameType HostNameType {
460 EnsureAbsoluteUri ();
461 UriHostNameType ret = CheckHostName (Host);
462 if (ret != UriHostNameType.Unknown)
466 return UriHostNameType.Basic;
468 return (IsFile) ? UriHostNameType.Basic : ret;
473 public bool IsDefaultPort {
475 EnsureAbsoluteUri ();
476 return GetDefaultPort (Scheme) == port;
482 EnsureAbsoluteUri ();
483 return (Scheme == UriSchemeFile);
487 public bool IsLoopback {
489 EnsureAbsoluteUri ();
491 if (Host.Length == 0) {
495 if (host == "loopback" || host == "localhost")
499 if (IPAddress.TryParse (host, out result))
500 if (IPAddress.Loopback.Equals (result))
504 if (IPv6Address.TryParse (host, out result6)){
505 if (IPv6Address.IsLoopback (result6))
514 // rule: This should be true only if
515 // - uri string starts from "\\", or
516 // - uri string starts from "//" (Samba way)
518 EnsureAbsoluteUri ();
523 public string LocalPath {
525 EnsureAbsoluteUri ();
526 if (cachedLocalPath != null)
527 return cachedLocalPath;
531 bool windows = (path.Length > 3 && path [1] == ':' &&
532 (path [2] == '\\' || path [2] == '/'));
535 string p = Unescape (path);
536 bool replace = windows;
538 replace |= (System.IO.Path.DirectorySeparatorChar == '\\');
541 cachedLocalPath = p.Replace ('/', '\\');
545 // support *nix and W32 styles
546 if (path.Length > 1 && path [1] == ':')
547 cachedLocalPath = Unescape (path.Replace (Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));
549 // LAMESPEC: ok, now we cannot determine
550 // if such URI like "file://foo/bar" is
551 // Windows UNC or unix file path, so
552 // they should be handled differently.
553 else if (System.IO.Path.DirectorySeparatorChar == '\\') {
555 if (path.Length > 0) {
556 if ((path.Length > 1) || (path[0] != '/')) {
557 h += path.Replace ('/', '\\');
560 cachedLocalPath = "\\\\" + Unescape (h);
562 cachedLocalPath = Unescape (path);
564 if (cachedLocalPath.Length == 0)
565 cachedLocalPath = Path.DirectorySeparatorChar.ToString ();
566 return cachedLocalPath;
570 public string PathAndQuery {
572 EnsureAbsoluteUri ();
579 EnsureAbsoluteUri ();
584 public string Query {
586 EnsureAbsoluteUri ();
591 public string Scheme {
593 EnsureAbsoluteUri ();
598 public string [] Segments {
600 EnsureAbsoluteUri ();
601 if (segments != null)
604 if (path.Length == 0) {
605 segments = new string [0];
609 string [] parts = path.Split ('/');
611 bool endSlash = path.EndsWith ("/");
612 if (parts.Length > 0 && endSlash) {
613 string [] newParts = new string [parts.Length - 1];
614 Array.Copy (parts, 0, newParts, 0, parts.Length - 1);
619 if (IsFile && path.Length > 1 && path [1] == ':') {
620 string [] newParts = new string [parts.Length + 1];
621 Array.Copy (parts, 1, newParts, 2, parts.Length - 1);
623 parts [0] = path.Substring (0, 2);
624 parts [1] = String.Empty;
628 int end = parts.Length;
630 if (i != end - 1 || endSlash)
638 public bool UserEscaped {
639 get { return userEscaped; }
642 public string UserInfo {
644 EnsureAbsoluteUri ();
649 [MonoTODO ("add support for IPv6 address")]
650 public string DnsSafeHost {
652 EnsureAbsoluteUri ();
653 return Unescape (Host);
663 get { return isAbsoluteUri; }
666 // LAMESPEC: source field is supplied in such case that this
667 // property makes sense. For such case that source field is
668 // not supplied (i.e. .ctor(Uri, string), this property
669 // makes no sense. To avoid silly regression it just returns
670 // ToString() value now. See bug #78374.
671 public string OriginalString {
672 get { return source != null ? source : ToString (); }
677 public static UriHostNameType CheckHostName (string name)
679 if (name == null || name.Length == 0)
680 return UriHostNameType.Unknown;
682 if (IsIPv4Address (name))
683 return UriHostNameType.IPv4;
685 if (IsDomainAddress (name))
686 return UriHostNameType.Dns;
689 if (IPv6Address.TryParse (name, out addr))
690 return UriHostNameType.IPv6;
692 return UriHostNameType.Unknown;
695 internal static bool IsIPv4Address (string name)
697 string [] captures = name.Split (new char [] {'.'});
698 if (captures.Length != 4)
701 for (int i = 0; i < 4; i++) {
704 length = captures [i].Length;
708 if (!UInt32.TryParse (captures [i], out number))
716 internal static bool IsDomainAddress (string name)
718 int len = name.Length;
721 for (int i = 0; i < len; i++) {
724 if (!Char.IsLetterOrDigit (c))
726 } else if (c == '.') {
728 } else if (!Char.IsLetterOrDigit (c) && c != '-' && c != '_') {
739 [Obsolete("This method does nothing, it has been obsoleted")]
740 protected virtual void Canonicalize ()
743 // This is flagged in the Microsoft documentation as used
744 // internally, no longer in use, and Obsolete.
748 [MonoTODO ("Find out what this should do")]
750 protected virtual void CheckSecurity ()
756 // defined in RFC3986 as = ALPHA *( ALPHA / DIGIT / "+" / "-" / ".")
757 public static bool CheckSchemeName (string schemeName)
759 if (schemeName == null || schemeName.Length == 0)
762 if (!IsAlpha (schemeName [0]))
765 int len = schemeName.Length;
766 for (int i = 1; i < len; i++) {
767 char c = schemeName [i];
768 if (!Char.IsDigit (c) && !IsAlpha (c) && c != '.' && c != '+' && c != '-')
775 private static bool IsAlpha (char c)
777 // as defined in rfc2234
778 // %x41-5A / %x61-7A (A-Z / a-z)
780 return (((i >= 0x41) && (i <= 0x5A)) || ((i >= 0x61) && (i <= 0x7A)));
783 public override bool Equals (object comparant)
785 if (comparant == null)
788 Uri uri = comparant as Uri;
789 if ((object) uri == null) {
790 string s = comparant as String;
796 return InternalEquals (uri);
799 // Assumes: uri != null
800 bool InternalEquals (Uri uri)
802 if (this.isAbsoluteUri != uri.isAbsoluteUri)
804 if (!this.isAbsoluteUri)
805 return this.source == uri.source;
807 CultureInfo inv = CultureInfo.InvariantCulture;
808 return this.scheme.ToLower (inv) == uri.scheme.ToLower (inv)
809 && this.host.ToLower (inv) == uri.host.ToLower (inv)
810 && this.port == uri.port
811 && this.query == uri.query
812 && this.path == uri.path;
815 public static bool operator == (Uri u1, Uri u2)
817 return object.Equals(u1, u2);
820 public static bool operator != (Uri u1, Uri u2)
825 public override int GetHashCode ()
827 if (cachedHashCode == 0) {
828 CultureInfo inv = CultureInfo.InvariantCulture;
830 cachedHashCode = scheme.ToLower (inv).GetHashCode ()
831 ^ host.ToLower (inv).GetHashCode ()
833 ^ query.GetHashCode ()
834 ^ path.GetHashCode ();
837 cachedHashCode = source.GetHashCode ();
840 return cachedHashCode;
843 public string GetLeftPart (UriPartial part)
845 EnsureAbsoluteUri ();
848 case UriPartial.Scheme :
849 return scheme + GetOpaqueWiseSchemeDelimiter ();
850 case UriPartial.Authority :
851 if ((scheme == Uri.UriSchemeMailto) || (scheme == Uri.UriSchemeNews))
854 StringBuilder s = new StringBuilder ();
856 s.Append (GetOpaqueWiseSchemeDelimiter ());
857 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
858 s.Append ('/'); // win32 file
859 if (userinfo.Length > 0)
860 s.Append (userinfo).Append ('@');
862 defaultPort = GetDefaultPort (scheme);
863 if ((port != -1) && (port != defaultPort))
864 s.Append (':').Append (port);
865 return s.ToString ();
866 case UriPartial.Path :
867 StringBuilder sb = new StringBuilder ();
869 sb.Append (GetOpaqueWiseSchemeDelimiter ());
870 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
871 sb.Append ('/'); // win32 file
872 if (userinfo.Length > 0)
873 sb.Append (userinfo).Append ('@');
875 defaultPort = GetDefaultPort (scheme);
876 if ((port != -1) && (port != defaultPort))
877 sb.Append (':').Append (port);
879 if (path.Length > 0) {
886 sb.Append (Reduce (path, CompactEscaped (Scheme)));
890 return sb.ToString ();
895 public static int FromHex (char digit)
897 if ('0' <= digit && digit <= '9') {
898 return (int) (digit - '0');
901 if ('a' <= digit && digit <= 'f')
902 return (int) (digit - 'a' + 10);
904 if ('A' <= digit && digit <= 'F')
905 return (int) (digit - 'A' + 10);
907 throw new ArgumentException ("digit");
910 public static string HexEscape (char character)
912 if (character > 255) {
913 throw new ArgumentOutOfRangeException ("character");
916 return "%" + hexUpperChars [((character & 0xf0) >> 4)]
917 + hexUpperChars [((character & 0x0f))];
920 public static char HexUnescape (string pattern, ref int index)
923 throw new ArgumentException ("pattern");
925 if (index < 0 || index >= pattern.Length)
926 throw new ArgumentOutOfRangeException ("index");
928 if (!IsHexEncoding (pattern, index))
929 return pattern [index++];
932 int msb = FromHex (pattern [index++]);
933 int lsb = FromHex (pattern [index++]);
934 return (char) ((msb << 4) | lsb);
937 public static bool IsHexDigit (char digit)
939 return (('0' <= digit && digit <= '9') ||
940 ('a' <= digit && digit <= 'f') ||
941 ('A' <= digit && digit <= 'F'));
944 public static bool IsHexEncoding (string pattern, int index)
946 if ((index + 3) > pattern.Length)
949 return ((pattern [index++] == '%') &&
950 IsHexDigit (pattern [index++]) &&
951 IsHexDigit (pattern [index]));
955 // Implemented by copying most of the MakeRelative code
957 public Uri MakeRelativeUri (Uri uri)
960 throw new ArgumentNullException ("uri");
962 if (Host != uri.Host || Scheme != uri.Scheme)
965 string result = String.Empty;
966 if (this.path != uri.path){
967 string [] segments = this.Segments;
968 string [] segments2 = uri.Segments;
971 int max = Math.Min (segments.Length, segments2.Length);
973 if (segments [k] != segments2 [k])
976 for (int i = k + 1; i < segments.Length; i++)
978 for (int i = k; i < segments2.Length; i++)
979 result += segments2 [i];
982 uri.AppendQueryAndFragment (ref result);
984 return new Uri (result, UriKind.Relative);
987 [Obsolete ("Use MakeRelativeUri(Uri uri) instead.")]
988 public string MakeRelative (Uri toUri)
990 if ((this.Scheme != toUri.Scheme) ||
991 (this.Authority != toUri.Authority))
992 return toUri.ToString ();
994 string result = String.Empty;
995 if (this.path != toUri.path){
996 string [] segments = this.Segments;
997 string [] segments2 = toUri.Segments;
999 int max = Math.Min (segments.Length, segments2.Length);
1000 for (; k < max; k++)
1001 if (segments [k] != segments2 [k])
1004 for (int i = k + 1; i < segments.Length; i++)
1006 for (int i = k; i < segments2.Length; i++)
1007 result += segments2 [i];
1010 // Important: MakeRelative does not append fragment or query.
1015 void AppendQueryAndFragment (ref string result)
1017 if (query.Length > 0) {
1018 string q = query [0] == '?' ? '?' + Unescape (query.Substring (1), false) : Unescape (query, false);
1021 if (fragment.Length > 0)
1025 public override string ToString ()
1027 if (cachedToString != null)
1028 return cachedToString;
1031 cachedToString = Unescape (GetLeftPart (UriPartial.Path), true);
1033 // Everything is contained in path in this case.
1034 cachedToString = Unescape (path);
1037 AppendQueryAndFragment (ref cachedToString);
1038 return cachedToString;
1041 protected void GetObjectData (SerializationInfo info, StreamingContext context)
1043 if (this.isAbsoluteUri) {
1044 info.AddValue ("AbsoluteUri", this.AbsoluteUri);
1046 info.AddValue("AbsoluteUri", String.Empty);
1047 info.AddValue("RelativeUri", this.OriginalString);
1051 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
1053 GetObjectData (info, context);
1060 protected virtual void Escape ()
1062 path = EscapeString (path);
1066 static string EscapeString (string str)
1069 protected static string EscapeString (string str)
1072 return EscapeString (str, false, true, true);
1075 internal static string EscapeString (string str, bool escapeReserved, bool escapeHex, bool escapeBrackets)
1078 return String.Empty;
1080 StringBuilder s = new StringBuilder ();
1081 int len = str.Length;
1082 for (int i = 0; i < len; i++) {
1083 // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
1084 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
1085 // control = <US-ASCII coded characters 00-1F and 7F hexadecimal>
1086 // space = <US-ASCII coded character 20 hexadecimal>
1087 // delims = "<" | ">" | "#" | "%" | <">
1088 // unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
1090 // check for escape code already placed in str,
1091 // i.e. for encoding that follows the pattern
1092 // "%hexhex" in a string, where "hex" is a digit from 0-9
1093 // or a letter from A-F (case-insensitive).
1094 if (IsHexEncoding (str,i)) {
1095 // if ,yes , copy it as is
1096 s.Append(str.Substring (i, 3));
1101 byte [] data = Encoding.UTF8.GetBytes (new char[] {str[i]});
1102 int length = data.Length;
1103 for (int j = 0; j < length; j++) {
1104 char c = (char) data [j];
1105 if ((c <= 0x20) || (c >= 0x7f) ||
1106 ("<>%\"{}|\\^`".IndexOf (c) != -1) ||
1107 (escapeHex && (c == '#')) ||
1108 (escapeBrackets && (c == '[' || c == ']')) ||
1109 (escapeReserved && (";/?:@&=+$,".IndexOf (c) != -1))) {
1110 s.Append (HexEscape (c));
1117 return s.ToString ();
1120 // On .NET 1.x, this method is called from .ctor(). When overriden, we
1121 // can avoid the "absolute uri" constraints of the .ctor() by
1122 // overriding with custom code.
1123 [Obsolete("The method has been deprecated. It is not used by the system.")]
1124 protected virtual void Parse ()
1128 private void ParseUri (UriKind kind)
1130 Parse (kind, source);
1135 host = EscapeString (host, false, true, false);
1136 if (host.Length > 1 && host [0] != '[' && host [host.Length - 1] != ']') {
1137 // host name present (but not an IPv6 address)
1138 host = host.ToLower (CultureInfo.InvariantCulture);
1141 if (path.Length > 0) {
1142 path = EscapeString (path);
1147 string Unescape (string str)
1150 protected virtual string Unescape (string str)
1153 return Unescape (str, false);
1156 internal static string Unescape (string str, bool excludeSpecial)
1159 return String.Empty;
1160 StringBuilder s = new StringBuilder ();
1161 int len = str.Length;
1162 for (int i = 0; i < len; i++) {
1166 char x = HexUnescapeMultiByte (str, ref i, out surrogate);
1167 if (excludeSpecial && x == '#')
1169 else if (excludeSpecial && x == '%')
1171 else if (excludeSpecial && x == '?')
1175 if (surrogate != char.MinValue)
1176 s.Append (surrogate);
1182 return s.ToString ();
1188 private void ParseAsWindowsUNC (string uriString)
1190 scheme = UriSchemeFile;
1192 fragment = String.Empty;
1193 query = String.Empty;
1196 uriString = uriString.TrimStart (new char [] {'\\'});
1197 int pos = uriString.IndexOf ('\\');
1199 path = uriString.Substring (pos);
1200 host = uriString.Substring (0, pos);
1201 } else { // "\\\\server"
1203 path = String.Empty;
1205 path = path.Replace ("\\", "/");
1209 // Returns null on success, string with error on failure
1211 private string ParseAsWindowsAbsoluteFilePath (string uriString)
1213 if (uriString.Length > 2 && uriString [2] != '\\' && uriString [2] != '/')
1214 return "Relative file path is not allowed.";
1215 scheme = UriSchemeFile;
1216 host = String.Empty;
1218 path = uriString.Replace ("\\", "/");
1219 fragment = String.Empty;
1220 query = String.Empty;
1225 private void ParseAsUnixAbsoluteFilePath (string uriString)
1227 isUnixFilePath = true;
1228 scheme = UriSchemeFile;
1230 fragment = String.Empty;
1231 query = String.Empty;
1232 host = String.Empty;
1235 if (uriString.Length >= 2 && uriString [0] == '/' && uriString [1] == '/') {
1236 uriString = uriString.TrimStart (new char [] {'/'});
1237 // Now we don't regard //foo/bar as "foo" host.
1239 int pos = uriString.IndexOf ('/');
1241 path = '/' + uriString.Substring (pos + 1);
1242 host = uriString.Substring (0, pos);
1243 } else { // "///server"
1245 path = String.Empty;
1248 path = '/' + uriString;
1255 // This parse method will throw exceptions on failure
1257 private void Parse (UriKind kind, string uriString)
1259 if (uriString == null)
1260 throw new ArgumentNullException ("uriString");
1262 string s = ParseNoExceptions (kind, uriString);
1264 throw new UriFormatException (s);
1268 // This parse method will not throw exceptions on failure
1270 // Returns null on success, or a description of the error in the parsing
1272 private string ParseNoExceptions (UriKind kind, string uriString)
1277 // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1281 uriString = uriString.Trim();
1282 int len = uriString.Length;
1285 if (kind == UriKind.Relative || kind == UriKind.RelativeOrAbsolute){
1286 isAbsoluteUri = false;
1291 if (len <= 1 && (kind == UriKind.Absolute))
1292 return "Absolute URI is too short";
1297 // Identify Windows path, unix path, or standard URI.
1298 if (uriString [0] == '/' && Path.DirectorySeparatorChar == '/'){
1300 ParseAsUnixAbsoluteFilePath (uriString);
1302 isAbsoluteUri = false;
1304 if (kind == UriKind.Relative)
1305 isAbsoluteUri = false;
1308 } else if (uriString.Length >= 2 && uriString [0] == '\\' && uriString [1] == '\\') {
1310 ParseAsWindowsUNC (uriString);
1315 pos = uriString.IndexOf (':');
1317 if (kind == UriKind.Absolute)
1318 return "Invalid URI: The format of the URI could not be determined.";
1319 isAbsoluteUri = false;
1322 } else if (pos < 0) {
1324 isAbsoluteUri = false;
1327 } else if (pos == 1) {
1328 if (!IsAlpha (uriString [0])) {
1329 if (kind == UriKind.Absolute)
1330 return "URI scheme must start with a letter.";
1331 isAbsoluteUri = false;
1335 // This means 'a:' == windows full path.
1336 string msg = ParseAsWindowsAbsoluteFilePath (uriString);
1343 scheme = uriString.Substring (0, pos).ToLower (CultureInfo.InvariantCulture);
1345 // Check scheme name characters as specified in RFC2396.
1346 // Note: different checks in 1.x and 2.0
1347 if (!CheckSchemeName (scheme)) {
1348 if (kind == UriKind.Absolute)
1349 return Locale.GetText ("URI scheme must start with a letter and must consist of one of alphabet, digits, '+', '-' or '.' character.");
1350 isAbsoluteUri = false;
1355 // from here we're practically working on uriString.Substring(startpos,endpos-startpos)
1356 int startpos = pos + 1;
1357 int endpos = uriString.Length;
1360 pos = uriString.IndexOf ('#', startpos);
1361 if (!IsUnc && pos != -1) {
1363 fragment = uriString.Substring (pos);
1365 fragment = "#" + EscapeString (uriString.Substring (pos+1));
1371 pos = uriString.IndexOf ('?', startpos, endpos-startpos);
1373 query = uriString.Substring (pos, endpos-pos);
1376 query = EscapeString (query);
1380 if (IsPredefinedScheme (scheme) && scheme != UriSchemeMailto && scheme != UriSchemeNews && (
1381 (endpos-startpos < 2) ||
1382 (endpos-startpos >= 2 && uriString [startpos] == '/' && uriString [startpos+1] != '/')))
1383 return "Invalid URI: The Authority/Host could not be parsed.";
1386 bool startsWithSlashSlash = endpos-startpos >= 2 && uriString [startpos] == '/' && uriString [startpos+1] == '/';
1387 bool unixAbsPath = scheme == UriSchemeFile && startsWithSlashSlash && (endpos-startpos == 2 || uriString [startpos+2] == '/');
1388 bool windowsFilePath = false;
1389 if (startsWithSlashSlash) {
1390 if (kind == UriKind.Relative)
1391 return "Absolute URI when we expected a relative one";
1393 if (scheme != UriSchemeMailto && scheme != UriSchemeNews)
1396 if (scheme == UriSchemeFile) {
1397 int num_leading_slash = 2;
1398 for (int i = startpos; i < endpos; i++) {
1399 if (uriString [i] != '/')
1401 num_leading_slash++;
1403 if (num_leading_slash >= 4) {
1404 unixAbsPath = false;
1405 while (startpos < endpos && uriString[startpos] == '/') {
1408 } else if (num_leading_slash >= 3) {
1413 if (endpos - startpos > 1 && uriString [startpos + 1] == ':') {
1414 unixAbsPath = false;
1415 windowsFilePath = true;
1418 } else if (!IsPredefinedScheme (scheme)) {
1419 path = uriString.Substring(startpos, endpos-startpos);
1420 isOpaquePart = true;
1428 pos = uriString.IndexOf ('/', startpos, endpos-startpos);
1429 if (pos == -1 && windowsFilePath)
1430 pos = uriString.IndexOf ('\\', startpos, endpos-startpos);
1434 if ((scheme != Uri.UriSchemeMailto) &&
1436 (scheme != Uri.UriSchemeFile) &&
1438 (scheme != Uri.UriSchemeNews))
1441 path = uriString.Substring (pos, endpos-pos);
1449 pos = uriString.IndexOf ('@', startpos, endpos-startpos);
1451 userinfo = uriString.Substring (startpos, pos-startpos);
1460 pos = uriString.LastIndexOf (':', endpos-1, endpos-startpos);
1461 if (pos != -1 && pos != endpos - 1) {
1462 string portStr = uriString.Substring(pos + 1, endpos - (pos + 1));
1463 if (portStr.Length > 0 && portStr[portStr.Length - 1] != ']') {
1464 if (!Int32.TryParse (portStr, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) ||
1465 port < 0 || port > UInt16.MaxValue)
1466 return "Invalid URI: Invalid port number";
1470 port = GetDefaultPort (scheme);
1475 port = GetDefaultPort (scheme);
1480 uriString = uriString.Substring(startpos, endpos-startpos);
1484 path = Reduce ('/' + uriString, true);
1485 host = String.Empty;
1486 } else if (host.Length == 2 && host [1] == ':') {
1489 host = String.Empty;
1490 } else if (isUnixFilePath) {
1491 uriString = "//" + uriString;
1492 host = String.Empty;
1493 } else if (scheme == UriSchemeFile) {
1495 } else if (scheme == UriSchemeNews) {
1496 // no host for 'news', misinterpreted path
1497 if (host.Length > 0) {
1499 host = String.Empty;
1501 } else if (host.Length == 0 &&
1502 (scheme == UriSchemeHttp || scheme == UriSchemeGopher || scheme == UriSchemeNntp ||
1503 scheme == UriSchemeHttps || scheme == UriSchemeFtp)) {
1504 return "Invalid URI: The hostname could not be parsed";
1507 bool badhost = ((host.Length > 0) && (CheckHostName (host) == UriHostNameType.Unknown));
1508 if (!badhost && (host.Length > 1) && (host[0] == '[') && (host[host.Length - 1] == ']')) {
1509 IPv6Address ipv6addr;
1511 if (IPv6Address.TryParse (host, out ipv6addr))
1512 host = "[" + ipv6addr.ToString (true) + "]";
1516 if (badhost && (Parser is DefaultUriParser || Parser == null))
1517 return Locale.GetText ("Invalid URI: The hostname could not be parsed. (" + host + ")");
1519 UriFormatException ex = null;
1521 Parser.InitializeAndValidate (this, out ex);
1525 if ((scheme != Uri.UriSchemeMailto) &&
1526 (scheme != Uri.UriSchemeNews) &&
1527 (scheme != Uri.UriSchemeFile)) {
1528 path = Reduce (path, CompactEscaped (scheme));
1534 private static bool CompactEscaped (string scheme)
1547 // This is called "compacting" in the MSDN documentation
1548 private static string Reduce (string path, bool compact_escaped)
1550 // quick out, allocation-free, for a common case
1554 StringBuilder res = new StringBuilder();
1556 if (compact_escaped) {
1557 // replace '\', %5C ('\') and %2f ('/') into '/'
1558 // other escaped values seems to survive this step
1559 for (int i=0; i < path.Length; i++) {
1566 if (i < path.Length - 2) {
1567 char c1 = path [i + 1];
1568 char c2 = Char.ToUpper (path [i + 2]);
1569 if (((c1 == '2') && (c2 == 'F')) || ((c1 == '5') && (c2 == 'C'))) {
1584 path = res.ToString ();
1586 path = path.Replace ('\\', '/');
1589 ArrayList result = new ArrayList ();
1592 for (int startpos = 0; startpos < path.Length; ) {
1593 int endpos = path.IndexOf('/', startpos);
1594 if (endpos == -1) endpos = path.Length;
1595 string current = path.Substring (startpos, endpos-startpos);
1596 startpos = endpos + 1;
1597 if ((begin && current.Length == 0) || current == "." )
1601 if (current == "..") {
1602 int resultCount = result.Count;
1603 // in 2.0 profile, skip leading ".." parts
1604 if (resultCount == 0) {
1608 result.RemoveAt (resultCount - 1);
1612 result.Add (current);
1615 if (result.Count == 0)
1619 if (path [0] == '/')
1623 foreach (string part in result) {
1632 if (path.EndsWith ("/"))
1635 return res.ToString();
1638 // A variant of HexUnescape() which can decode multi-byte escaped
1639 // sequences such as (e.g.) %E3%81%8B into a single character
1640 private static char HexUnescapeMultiByte (string pattern, ref int index, out char surrogate)
1642 surrogate = char.MinValue;
1644 if (pattern == null)
1645 throw new ArgumentException ("pattern");
1647 if (index < 0 || index >= pattern.Length)
1648 throw new ArgumentOutOfRangeException ("index");
1650 if (!IsHexEncoding (pattern, index))
1651 return pattern [index++];
1653 int orig_index = index++;
1654 int msb = FromHex (pattern [index++]);
1655 int lsb = FromHex (pattern [index++]);
1657 // We might be dealing with a multi-byte character:
1658 // The number of ones at the top-end of the first byte will tell us
1659 // how many bytes will make up this character.
1662 while ((msb_copy & 0x8) == 0x8) {
1667 // We might be dealing with a single-byte character:
1668 // If there was only 0 or 1 leading ones then we're not dealing
1669 // with a multi-byte character.
1671 return (char) ((msb << 4) | lsb);
1673 // Now that we know how many bytes *should* follow, we'll check them
1674 // to ensure we are dealing with a valid multi-byte character.
1675 byte [] chars = new byte [num_bytes];
1676 bool all_invalid = false;
1677 chars[0] = (byte) ((msb << 4) | lsb);
1679 for (int i = 1; i < num_bytes; i++) {
1680 if (!IsHexEncoding (pattern, index++)) {
1685 // All following bytes must be in the form 10xxxxxx
1686 int cur_msb = FromHex (pattern [index++]);
1687 if ((cur_msb & 0xc) != 0x8) {
1692 int cur_lsb = FromHex (pattern [index++]);
1693 chars[i] = (byte) ((cur_msb << 4) | cur_lsb);
1696 // If what looked like a multi-byte character is invalid, then we'll
1697 // just return the first byte as a single byte character.
1699 index = orig_index + 3;
1700 return (char) chars[0];
1703 // Otherwise, we're dealing with a valid multi-byte character.
1704 // We need to ignore the leading ones from the first byte:
1705 byte mask = (byte) 0xFF;
1706 mask >>= (num_bytes + 1);
1707 int result = chars[0] & mask;
1709 // The result will now be built up from the following bytes.
1710 for (int i = 1; i < num_bytes; i++) {
1711 // Ignore upper two bits
1713 result |= (chars[i] & 0x3F);
1716 if (result <= 0xFFFF) {
1717 return (char) result;
1719 // We need to handle this as a UTF16 surrogate (i.e. return
1722 surrogate = (char) ((result & 0x3FF) | 0xDC00);
1723 return (char) ((result >> 10) | 0xD800);
1727 private struct UriScheme
1729 public string scheme;
1730 public string delimiter;
1731 public int defaultPort;
1733 public UriScheme (string s, string d, int p)
1741 static UriScheme [] schemes = new UriScheme [] {
1742 new UriScheme (UriSchemeHttp, SchemeDelimiter, 80),
1743 new UriScheme (UriSchemeHttps, SchemeDelimiter, 443),
1744 new UriScheme (UriSchemeFtp, SchemeDelimiter, 21),
1745 new UriScheme (UriSchemeFile, SchemeDelimiter, -1),
1746 new UriScheme (UriSchemeMailto, ":", 25),
1747 new UriScheme (UriSchemeNews, ":", 119),
1748 new UriScheme (UriSchemeNntp, SchemeDelimiter, 119),
1749 new UriScheme (UriSchemeGopher, SchemeDelimiter, 70),
1752 internal static string GetSchemeDelimiter (string scheme)
1754 for (int i = 0; i < schemes.Length; i++)
1755 if (schemes [i].scheme == scheme)
1756 return schemes [i].delimiter;
1757 return Uri.SchemeDelimiter;
1760 internal static int GetDefaultPort (string scheme)
1762 UriParser parser = UriParser.GetParser (scheme);
1765 return parser.DefaultPort;
1768 private string GetOpaqueWiseSchemeDelimiter ()
1773 return GetSchemeDelimiter (scheme);
1777 protected virtual bool IsBadFileSystemCharacter (char ch)
1779 // It does not always overlap with InvalidPathChars.
1780 int chInt = (int) ch;
1781 if (chInt < 32 || (chInt < 64 && chInt > 57))
1800 protected static bool IsExcludedCharacter (char ch)
1802 if (ch <= 32 || ch >= 127)
1805 if (ch == '"' || ch == '#' || ch == '%' || ch == '<' ||
1806 ch == '>' || ch == '[' || ch == '\\' || ch == ']' ||
1807 ch == '^' || ch == '`' || ch == '{' || ch == '|' ||
1813 internal static bool MaybeUri (string s)
1815 int p = s.IndexOf (':');
1822 return IsPredefinedScheme (s.Substring (0, p));
1825 private static bool IsPredefinedScheme (string scheme)
1845 protected virtual bool IsReservedCharacter (char ch)
1847 if (ch == '$' || ch == '&' || ch == '+' || ch == ',' ||
1848 ch == '/' || ch == ':' || ch == ';' || ch == '=' ||
1855 private UriParser parser;
1857 private UriParser Parser {
1859 if (parser == null) {
1860 parser = UriParser.GetParser (Scheme);
1861 // no specific parser ? then use a default one
1863 parser = new DefaultUriParser ("*");
1867 set { parser = value; }
1870 public string GetComponents (UriComponents components, UriFormat format)
1872 return Parser.GetComponents (this, components, format);
1875 public bool IsBaseOf (Uri uri)
1877 return Parser.IsBaseOf (this, uri);
1880 public bool IsWellFormedOriginalString ()
1882 // funny, but it does not use the Parser's IsWellFormedOriginalString().
1883 // Also, it seems we need to *not* escape hex.
1884 return EscapeString (OriginalString, false, false, true) == OriginalString;
1889 private const int MaxUriLength = 32766;
1891 public static int Compare (Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType)
1893 if ((comparisonType < StringComparison.CurrentCulture) || (comparisonType > StringComparison.OrdinalIgnoreCase)) {
1894 string msg = Locale.GetText ("Invalid StringComparison value '{0}'", comparisonType);
1895 throw new ArgumentException ("comparisonType", msg);
1898 if ((uri1 == null) && (uri2 == null))
1901 string s1 = uri1.GetComponents (partsToCompare, compareFormat);
1902 string s2 = uri2.GetComponents (partsToCompare, compareFormat);
1903 return String.Compare (s1, s2, comparisonType);
1907 // The rules for EscapeDataString
1909 static bool NeedToEscapeDataChar (char b)
1911 return !((b >= 'A' && b <= 'Z') ||
1912 (b >= 'a' && b <= 'z') ||
1913 (b >= '0' && b <= '9') ||
1914 b == '_' || b == '~' || b == '!' || b == '\'' ||
1915 b == '(' || b == ')' || b == '*' || b == '-' || b == '.');
1918 public static string EscapeDataString (string stringToEscape)
1920 if (stringToEscape == null)
1921 throw new ArgumentNullException ("stringToEscape");
1923 if (stringToEscape.Length > MaxUriLength) {
1924 string msg = Locale.GetText ("Uri is longer than the maximum {0} characters.");
1925 throw new UriFormatException (msg);
1927 bool escape = false;
1928 foreach (char c in stringToEscape){
1929 if (NeedToEscapeDataChar (c)){
1935 return stringToEscape;
1938 StringBuilder sb = new StringBuilder ();
1939 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
1940 foreach (byte b in bytes){
1941 if (NeedToEscapeDataChar ((char) b))
1942 sb.Append (HexEscape ((char) b));
1944 sb.Append ((char) b);
1946 return sb.ToString ();
1950 // The rules for EscapeUriString
1952 static bool NeedToEscapeUriChar (char b)
1954 return !((b >= 'A' && b <= 'Z') ||
1955 (b >= 'a' && b <= 'z') ||
1956 (b >= '&' && b <= ';') ||
1957 b == '!' || b == '#' || b == '$' || b == '=' ||
1958 b == '?' || b == '@' || b == '_' || b == '~');
1961 public static string EscapeUriString (string stringToEscape)
1963 if (stringToEscape == null)
1964 throw new ArgumentNullException ("stringToEscape");
1966 if (stringToEscape.Length > MaxUriLength) {
1967 string msg = Locale.GetText ("Uri is longer than the maximum {0} characters.");
1968 throw new UriFormatException (msg);
1971 bool escape = false;
1972 foreach (char c in stringToEscape){
1973 if (NeedToEscapeUriChar (c)){
1979 return stringToEscape;
1981 StringBuilder sb = new StringBuilder ();
1982 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
1983 foreach (byte b in bytes){
1984 if (NeedToEscapeUriChar ((char) b))
1985 sb.Append (HexEscape ((char) b));
1987 sb.Append ((char) b);
1989 return sb.ToString ();
1992 public static bool IsWellFormedUriString (string uriString, UriKind uriKind)
1994 if (uriString == null)
1998 if (Uri.TryCreate (uriString, uriKind, out uri))
1999 return uri.IsWellFormedOriginalString ();
2003 public static bool TryCreate (string uriString, UriKind uriKind, out Uri result)
2007 Uri r = new Uri (uriString, uriKind, out success);
2016 // [MonoTODO ("rework code to avoid exception catching")]
2017 public static bool TryCreate (Uri baseUri, string relativeUri, out Uri result)
2020 // FIXME: this should call UriParser.Resolve
2021 result = new Uri (baseUri, relativeUri);
2023 } catch (UriFormatException) {
2029 //[MonoTODO ("rework code to avoid exception catching")]
2030 public static bool TryCreate (Uri baseUri, Uri relativeUri, out Uri result)
2033 // FIXME: this should call UriParser.Resolve
2034 result = new Uri (baseUri, relativeUri.OriginalString);
2036 } catch (UriFormatException) {
2042 public static string UnescapeDataString (string stringToUnescape)
2044 if (stringToUnescape == null)
2045 throw new ArgumentNullException ("stringToUnescape");
2047 if (stringToUnescape.IndexOf ('%') == -1 && stringToUnescape.IndexOf ('+') == -1)
2048 return stringToUnescape;
2050 StringBuilder output = new StringBuilder ();
2051 long len = stringToUnescape.Length;
2052 MemoryStream bytes = new MemoryStream ();
2055 for (int i = 0; i < len; i++) {
2056 if (stringToUnescape [i] == '%' && i + 2 < len && stringToUnescape [i + 1] != '%') {
2057 if (stringToUnescape [i + 1] == 'u' && i + 5 < len) {
2058 if (bytes.Length > 0) {
2059 output.Append (GetChars (bytes, Encoding.UTF8));
2060 bytes.SetLength (0);
2063 xchar = GetChar (stringToUnescape, i + 2, 4);
2065 output.Append ((char) xchar);
2069 output.Append ('%');
2072 else if ((xchar = GetChar (stringToUnescape, i + 1, 2)) != -1) {
2073 bytes.WriteByte ((byte) xchar);
2077 output.Append ('%');
2082 if (bytes.Length > 0) {
2083 output.Append (GetChars (bytes, Encoding.UTF8));
2084 bytes.SetLength (0);
2087 output.Append (stringToUnescape [i]);
2090 if (bytes.Length > 0) {
2091 output.Append (GetChars (bytes, Encoding.UTF8));
2095 return output.ToString ();
2098 private static int GetInt (byte b)
2101 if (c >= '0' && c <= '9')
2104 if (c >= 'a' && c <= 'f')
2105 return c - 'a' + 10;
2107 if (c >= 'A' && c <= 'F')
2108 return c - 'A' + 10;
2113 private static int GetChar (string str, int offset, int length)
2116 int end = length + offset;
2117 for (int i = offset; i < end; i++) {
2122 int current = GetInt ((byte) c);
2125 val = (val << 4) + current;
2131 private static char [] GetChars (MemoryStream b, Encoding e)
2133 return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
2137 private void EnsureAbsoluteUri ()
2140 throw new InvalidOperationException ("This operation is not supported for a relative URI.");