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,
120 StreamingContext streamingContext) :
121 this (serializationInfo.GetString ("AbsoluteUri"), true)
125 public Uri (string uriString, UriKind uriKind)
131 case UriKind.Absolute:
133 throw new UriFormatException("Invalid URI: The format of the URI could not be "
136 case UriKind.Relative:
138 throw new UriFormatException("Invalid URI: The format of the URI could not be "
139 + "determined because the parameter 'uriString' represents an absolute URI.");
141 case UriKind.RelativeOrAbsolute:
144 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
145 throw new ArgumentException (msg);
150 // An exception-less constructor, returns success
151 // condition on the out parameter `success'.
153 Uri (string uriString, UriKind uriKind, out bool success)
155 if (uriString == null) {
160 if (uriKind != UriKind.RelativeOrAbsolute &&
161 uriKind != UriKind.Absolute &&
162 uriKind != UriKind.Relative) {
163 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
164 throw new ArgumentException (msg);
168 if (ParseNoExceptions (uriKind, uriString) != null)
174 case UriKind.Absolute:
178 case UriKind.Relative:
182 case UriKind.RelativeOrAbsolute:
191 public Uri (Uri baseUri, Uri relativeUri)
193 Merge (baseUri, relativeUri == null ? String.Empty : relativeUri.OriginalString);
194 // FIXME: this should call UriParser.Resolve
197 // note: doc says that dontEscape is always false but tests show otherwise
199 public Uri (string uriString, bool dontEscape)
201 userEscaped = dontEscape;
203 ParseUri (UriKind.Absolute);
205 throw new UriFormatException("Invalid URI: The format of the URI could not be "
206 + "determined: " + uriString);
209 public Uri (Uri baseUri, string relativeUri)
211 Merge (baseUri, relativeUri);
212 // FIXME: this should call UriParser.Resolve
215 [Obsolete ("dontEscape is always false")]
216 public Uri (Uri baseUri, string relativeUri, bool dontEscape)
218 userEscaped = dontEscape;
219 Merge (baseUri, relativeUri);
222 private void Merge (Uri baseUri, string relativeUri)
225 throw new ArgumentNullException ("baseUri");
226 if (!baseUri.IsAbsoluteUri)
227 throw new ArgumentOutOfRangeException ("baseUri");
228 if (relativeUri == null)
229 relativeUri = String.Empty;
231 // See RFC 2396 Par 5.2 and Appendix C
233 // Check Windows UNC (for // it is scheme/host separator)
234 if (relativeUri.Length >= 2 && relativeUri [0] == '\\' && relativeUri [1] == '\\') {
235 source = relativeUri;
236 ParseUri (UriKind.Absolute);
240 int pos = relativeUri.IndexOf (':');
243 int pos2 = relativeUri.IndexOfAny (new char [] {'/', '\\', '?'});
245 // pos2 < 0 ... e.g. mailto
246 // pos2 > pos ... to block ':' in query part
247 if (pos2 > pos || pos2 < 0) {
248 // in some cases, it is equivanent to new Uri (relativeUri, dontEscape):
249 // 1) when the URI scheme in the
250 // relative path is different from that
251 // of the baseUri, or
252 // 2) the URI scheme is non-standard
253 // ones (non-standard URIs are always
254 // treated as absolute here), or
255 // 3) the relative URI path is absolute.
256 if (String.CompareOrdinal (baseUri.Scheme, 0, relativeUri, 0, pos) != 0 ||
257 !IsPredefinedScheme (baseUri.Scheme) ||
258 relativeUri.Length > pos + 1 &&
259 relativeUri [pos + 1] == '/') {
260 source = relativeUri;
261 ParseUri (UriKind.Absolute);
265 relativeUri = relativeUri.Substring (pos + 1);
269 this.scheme = baseUri.scheme;
270 this.host = baseUri.host;
271 this.port = baseUri.port;
272 this.userinfo = baseUri.userinfo;
273 this.isUnc = baseUri.isUnc;
274 this.isUnixFilePath = baseUri.isUnixFilePath;
275 this.isOpaquePart = baseUri.isOpaquePart;
277 if (relativeUri == String.Empty) {
278 this.path = baseUri.path;
279 this.query = baseUri.query;
280 this.fragment = baseUri.fragment;
285 // Note that in relative constructor, file URI cannot handle '#' as a filename character, but just regarded as a fragment identifier.
286 pos = relativeUri.IndexOf ('#');
289 fragment = relativeUri.Substring (pos);
291 fragment = "#" + EscapeString (relativeUri.Substring (pos+1));
292 relativeUri = relativeUri.Substring (0, pos);
296 pos = relativeUri.IndexOf ('?');
298 query = relativeUri.Substring (pos);
300 query = EscapeString (query);
301 relativeUri = relativeUri.Substring (0, pos);
304 if (relativeUri.Length > 0 && relativeUri [0] == '/') {
305 if (relativeUri.Length > 1 && relativeUri [1] == '/') {
306 source = scheme + ':' + relativeUri;
307 ParseUri (UriKind.Absolute);
312 path = EscapeString (path);
319 if (relativeUri.Length > 0 || query.Length > 0) {
320 pos = path.LastIndexOf ('/');
322 path = path.Substring (0, pos + 1);
325 if(relativeUri.Length == 0)
334 pos = path.IndexOf ("./", startIndex);
338 path = path.Remove (0, 2);
339 else if (path [pos - 1] != '.')
340 path = path.Remove (pos, 2);
342 startIndex = pos + 1;
346 if (path.Length > 1 &&
347 path [path.Length - 1] == '.' &&
348 path [path.Length - 2] == '/')
349 path = path.Remove (path.Length - 1, 1);
354 pos = path.IndexOf ("/../", startIndex);
361 int pos2 = path.LastIndexOf ('/', pos - 1);
363 startIndex = pos + 1;
365 if (path.Substring (pos2 + 1, pos - pos2 - 1) != "..")
366 path = path.Remove (pos2 + 1, pos - pos2 + 3);
368 startIndex = pos + 1;
373 if (path.Length > 3 && path.EndsWith ("/..")) {
374 pos = path.LastIndexOf ('/', path.Length - 4);
376 if (path.Substring (pos + 1, path.Length - pos - 4) != "..")
377 path = path.Remove (pos + 1, path.Length - pos - 1);
381 path = EscapeString (path);
386 public string AbsolutePath {
388 EnsureAbsoluteUri ();
392 // faster (mailto) and special (file) cases
395 if (path.Length == 0) {
396 string start = Scheme + SchemeDelimiter;
397 if (path.StartsWith (start))
407 public string AbsoluteUri {
409 EnsureAbsoluteUri ();
410 if (cachedAbsoluteUri == null) {
411 cachedAbsoluteUri = GetLeftPart (UriPartial.Path);
412 if (query.Length > 0)
413 cachedAbsoluteUri += query;
414 if (fragment.Length > 0)
415 cachedAbsoluteUri += fragment;
417 return cachedAbsoluteUri;
421 public string Authority {
423 EnsureAbsoluteUri ();
424 return (GetDefaultPort (Scheme) == port)
425 ? host : host + ":" + port;
429 public string Fragment {
431 EnsureAbsoluteUri ();
438 EnsureAbsoluteUri ();
443 public UriHostNameType HostNameType {
445 EnsureAbsoluteUri ();
446 UriHostNameType ret = CheckHostName (Host);
447 if (ret != UriHostNameType.Unknown)
451 return UriHostNameType.Basic;
453 return (IsFile) ? UriHostNameType.Basic : ret;
458 public bool IsDefaultPort {
460 EnsureAbsoluteUri ();
461 return GetDefaultPort (Scheme) == port;
467 EnsureAbsoluteUri ();
468 return (Scheme == UriSchemeFile);
472 public bool IsLoopback {
474 EnsureAbsoluteUri ();
476 if (Host.Length == 0) {
480 if (host == "loopback" || host == "localhost")
484 if (IPAddress.TryParse (host, out result))
485 if (IPAddress.Loopback.Equals (result))
489 if (IPv6Address.TryParse (host, out result6)){
490 if (IPv6Address.IsLoopback (result6))
499 // rule: This should be true only if
500 // - uri string starts from "\\", or
501 // - uri string starts from "//" (Samba way)
503 EnsureAbsoluteUri ();
508 public string LocalPath {
510 EnsureAbsoluteUri ();
511 if (cachedLocalPath != null)
512 return cachedLocalPath;
516 bool windows = (path.Length > 3 && path [1] == ':' &&
517 (path [2] == '\\' || path [2] == '/'));
520 string p = Unescape (path);
521 bool replace = windows;
523 replace |= (System.IO.Path.DirectorySeparatorChar == '\\');
526 cachedLocalPath = p.Replace ('/', '\\');
530 // support *nix and W32 styles
531 if (path.Length > 1 && path [1] == ':')
532 cachedLocalPath = Unescape (path.Replace (Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));
534 // LAMESPEC: ok, now we cannot determine
535 // if such URI like "file://foo/bar" is
536 // Windows UNC or unix file path, so
537 // they should be handled differently.
538 else if (System.IO.Path.DirectorySeparatorChar == '\\') {
540 if (path.Length > 0) {
541 if ((path.Length > 1) || (path[0] != '/')) {
542 h += path.Replace ('/', '\\');
545 cachedLocalPath = "\\\\" + Unescape (h);
547 cachedLocalPath = Unescape (path);
549 if (cachedLocalPath.Length == 0)
550 cachedLocalPath = Path.DirectorySeparatorChar.ToString ();
551 return cachedLocalPath;
555 public string PathAndQuery {
557 EnsureAbsoluteUri ();
564 EnsureAbsoluteUri ();
569 public string Query {
571 EnsureAbsoluteUri ();
576 public string Scheme {
578 EnsureAbsoluteUri ();
583 public string [] Segments {
585 EnsureAbsoluteUri ();
586 if (segments != null)
589 if (path.Length == 0) {
590 segments = new string [0];
594 string [] parts = path.Split ('/');
596 bool endSlash = path.EndsWith ("/");
597 if (parts.Length > 0 && endSlash) {
598 string [] newParts = new string [parts.Length - 1];
599 Array.Copy (parts, 0, newParts, 0, parts.Length - 1);
604 if (IsFile && path.Length > 1 && path [1] == ':') {
605 string [] newParts = new string [parts.Length + 1];
606 Array.Copy (parts, 1, newParts, 2, parts.Length - 1);
608 parts [0] = path.Substring (0, 2);
609 parts [1] = String.Empty;
613 int end = parts.Length;
615 if (i != end - 1 || endSlash)
623 public bool UserEscaped {
624 get { return userEscaped; }
627 public string UserInfo {
629 EnsureAbsoluteUri ();
634 [MonoTODO ("add support for IPv6 address")]
635 public string DnsSafeHost {
637 EnsureAbsoluteUri ();
638 return Unescape (Host);
642 public bool IsAbsoluteUri {
643 get { return isAbsoluteUri; }
646 // LAMESPEC: source field is supplied in such case that this
647 // property makes sense. For such case that source field is
648 // not supplied (i.e. .ctor(Uri, string), this property
649 // makes no sense. To avoid silly regression it just returns
650 // ToString() value now. See bug #78374.
651 public string OriginalString {
652 get { return source != null ? source : ToString (); }
657 public static UriHostNameType CheckHostName (string name)
659 if (name == null || name.Length == 0)
660 return UriHostNameType.Unknown;
662 if (IsIPv4Address (name))
663 return UriHostNameType.IPv4;
665 if (IsDomainAddress (name))
666 return UriHostNameType.Dns;
669 if (IPv6Address.TryParse (name, out addr))
670 return UriHostNameType.IPv6;
672 return UriHostNameType.Unknown;
675 internal static bool IsIPv4Address (string name)
677 string [] captures = name.Split (new char [] {'.'});
678 if (captures.Length != 4)
681 for (int i = 0; i < 4; i++) {
684 length = captures [i].Length;
688 if (!UInt32.TryParse (captures [i], out number))
696 internal static bool IsDomainAddress (string name)
698 int len = name.Length;
701 for (int i = 0; i < len; i++) {
704 if (!Char.IsLetterOrDigit (c))
706 } else if (c == '.') {
708 } else if (!Char.IsLetterOrDigit (c) && c != '-' && c != '_') {
719 [Obsolete("This method does nothing, it has been obsoleted")]
720 protected virtual void Canonicalize ()
723 // This is flagged in the Microsoft documentation as used
724 // internally, no longer in use, and Obsolete.
728 [MonoTODO ("Find out what this should do")]
730 protected virtual void CheckSecurity ()
736 // defined in RFC3986 as = ALPHA *( ALPHA / DIGIT / "+" / "-" / ".")
737 public static bool CheckSchemeName (string schemeName)
739 if (schemeName == null || schemeName.Length == 0)
742 if (!IsAlpha (schemeName [0]))
745 int len = schemeName.Length;
746 for (int i = 1; i < len; i++) {
747 char c = schemeName [i];
748 if (!Char.IsDigit (c) && !IsAlpha (c) && c != '.' && c != '+' && c != '-')
755 private static bool IsAlpha (char c)
757 // as defined in rfc2234
758 // %x41-5A / %x61-7A (A-Z / a-z)
760 return (((i >= 0x41) && (i <= 0x5A)) || ((i >= 0x61) && (i <= 0x7A)));
763 public override bool Equals (object comparant)
765 if (comparant == null)
768 Uri uri = comparant as Uri;
769 if ((object) uri == null) {
770 string s = comparant as String;
776 return InternalEquals (uri);
779 // Assumes: uri != null
780 bool InternalEquals (Uri uri)
782 if (this.isAbsoluteUri != uri.isAbsoluteUri)
784 if (!this.isAbsoluteUri)
785 return this.source == uri.source;
787 CultureInfo inv = CultureInfo.InvariantCulture;
788 return this.scheme.ToLower (inv) == uri.scheme.ToLower (inv)
789 && this.host.ToLower (inv) == uri.host.ToLower (inv)
790 && this.port == uri.port
791 && this.query == uri.query
792 && this.path == uri.path;
795 public static bool operator == (Uri u1, Uri u2)
797 return object.Equals(u1, u2);
800 public static bool operator != (Uri u1, Uri u2)
805 public override int GetHashCode ()
807 if (cachedHashCode == 0) {
808 CultureInfo inv = CultureInfo.InvariantCulture;
810 cachedHashCode = scheme.ToLower (inv).GetHashCode ()
811 ^ host.ToLower (inv).GetHashCode ()
813 ^ query.GetHashCode ()
814 ^ path.GetHashCode ();
817 cachedHashCode = source.GetHashCode ();
820 return cachedHashCode;
823 public string GetLeftPart (UriPartial part)
825 EnsureAbsoluteUri ();
828 case UriPartial.Scheme :
829 return scheme + GetOpaqueWiseSchemeDelimiter ();
830 case UriPartial.Authority :
831 if ((scheme == Uri.UriSchemeMailto) || (scheme == Uri.UriSchemeNews))
834 StringBuilder s = new StringBuilder ();
836 s.Append (GetOpaqueWiseSchemeDelimiter ());
837 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
838 s.Append ('/'); // win32 file
839 if (userinfo.Length > 0)
840 s.Append (userinfo).Append ('@');
842 defaultPort = GetDefaultPort (scheme);
843 if ((port != -1) && (port != defaultPort))
844 s.Append (':').Append (port);
845 return s.ToString ();
846 case UriPartial.Path :
847 StringBuilder sb = new StringBuilder ();
849 sb.Append (GetOpaqueWiseSchemeDelimiter ());
850 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
851 sb.Append ('/'); // win32 file
852 if (userinfo.Length > 0)
853 sb.Append (userinfo).Append ('@');
855 defaultPort = GetDefaultPort (scheme);
856 if ((port != -1) && (port != defaultPort))
857 sb.Append (':').Append (port);
859 if (path.Length > 0) {
866 sb.Append (Reduce (path));
870 return sb.ToString ();
875 public static int FromHex (char digit)
877 if ('0' <= digit && digit <= '9') {
878 return (int) (digit - '0');
881 if ('a' <= digit && digit <= 'f')
882 return (int) (digit - 'a' + 10);
884 if ('A' <= digit && digit <= 'F')
885 return (int) (digit - 'A' + 10);
887 throw new ArgumentException ("digit");
890 public static string HexEscape (char character)
892 if (character > 255) {
893 throw new ArgumentOutOfRangeException ("character");
896 return "%" + hexUpperChars [((character & 0xf0) >> 4)]
897 + hexUpperChars [((character & 0x0f))];
900 public static char HexUnescape (string pattern, ref int index)
903 throw new ArgumentException ("pattern");
905 if (index < 0 || index >= pattern.Length)
906 throw new ArgumentOutOfRangeException ("index");
908 if (!IsHexEncoding (pattern, index))
909 return pattern [index++];
912 int msb = FromHex (pattern [index++]);
913 int lsb = FromHex (pattern [index++]);
914 return (char) ((msb << 4) | lsb);
917 public static bool IsHexDigit (char digit)
919 return (('0' <= digit && digit <= '9') ||
920 ('a' <= digit && digit <= 'f') ||
921 ('A' <= digit && digit <= 'F'));
924 public static bool IsHexEncoding (string pattern, int index)
926 if ((index + 3) > pattern.Length)
929 return ((pattern [index++] == '%') &&
930 IsHexDigit (pattern [index++]) &&
931 IsHexDigit (pattern [index]));
935 // Implemented by copying most of the MakeRelative code
937 public Uri MakeRelativeUri (Uri uri)
940 throw new ArgumentNullException ("uri");
942 if (Host != uri.Host || Scheme != uri.Scheme)
945 string result = String.Empty;
946 if (this.path != uri.path){
947 string [] segments = this.Segments;
948 string [] segments2 = uri.Segments;
951 int max = Math.Min (segments.Length, segments2.Length);
953 if (segments [k] != segments2 [k])
956 for (int i = k + 1; i < segments.Length; i++)
958 for (int i = k; i < segments2.Length; i++)
959 result += segments2 [i];
962 uri.AppendQueryAndFragment (ref result);
964 return new Uri (result, UriKind.Relative);
967 [Obsolete ("Use MakeRelativeUri(Uri uri) instead.")]
968 public string MakeRelative (Uri toUri)
970 if ((this.Scheme != toUri.Scheme) ||
971 (this.Authority != toUri.Authority))
972 return toUri.ToString ();
974 string result = String.Empty;
975 if (this.path != toUri.path){
976 string [] segments = this.Segments;
977 string [] segments2 = toUri.Segments;
979 int max = Math.Min (segments.Length, segments2.Length);
981 if (segments [k] != segments2 [k])
984 for (int i = k + 1; i < segments.Length; i++)
986 for (int i = k; i < segments2.Length; i++)
987 result += segments2 [i];
990 // Important: MakeRelative does not append fragment or query.
995 void AppendQueryAndFragment (ref string result)
997 if (query.Length > 0) {
998 string q = query [0] == '?' ? '?' + Unescape (query.Substring (1), false) : Unescape (query, false);
1001 if (fragment.Length > 0)
1005 public override string ToString ()
1007 if (cachedToString != null)
1008 return cachedToString;
1011 cachedToString = Unescape (GetLeftPart (UriPartial.Path), true);
1013 // Everything is contained in path in this case.
1014 cachedToString = Unescape (path);
1017 AppendQueryAndFragment (ref cachedToString);
1018 return cachedToString;
1021 protected void GetObjectData (SerializationInfo info, StreamingContext context)
1023 info.AddValue ("AbsoluteUri", this.AbsoluteUri);
1026 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
1028 info.AddValue ("AbsoluteUri", this.AbsoluteUri);
1035 protected virtual void Escape ()
1037 path = EscapeString (path);
1041 static string EscapeString (string str)
1044 protected static string EscapeString (string str)
1047 return EscapeString (str, false, true, true);
1050 internal static string EscapeString (string str, bool escapeReserved, bool escapeHex, bool escapeBrackets)
1053 return String.Empty;
1055 StringBuilder s = new StringBuilder ();
1056 int len = str.Length;
1057 for (int i = 0; i < len; i++) {
1058 // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
1059 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
1060 // control = <US-ASCII coded characters 00-1F and 7F hexadecimal>
1061 // space = <US-ASCII coded character 20 hexadecimal>
1062 // delims = "<" | ">" | "#" | "%" | <">
1063 // unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
1065 // check for escape code already placed in str,
1066 // i.e. for encoding that follows the pattern
1067 // "%hexhex" in a string, where "hex" is a digit from 0-9
1068 // or a letter from A-F (case-insensitive).
1069 if (IsHexEncoding (str,i)) {
1070 // if ,yes , copy it as is
1071 s.Append(str.Substring (i, 3));
1076 byte [] data = Encoding.UTF8.GetBytes (new char[] {str[i]});
1077 int length = data.Length;
1078 for (int j = 0; j < length; j++) {
1079 char c = (char) data [j];
1080 if ((c <= 0x20) || (c >= 0x7f) ||
1081 ("<>%\"{}|\\^`".IndexOf (c) != -1) ||
1082 (escapeHex && (c == '#')) ||
1083 (escapeBrackets && (c == '[' || c == ']')) ||
1084 (escapeReserved && (";/?:@&=+$,".IndexOf (c) != -1))) {
1085 s.Append (HexEscape (c));
1092 return s.ToString ();
1095 // On .NET 1.x, this method is called from .ctor(). When overriden, we
1096 // can avoid the "absolute uri" constraints of the .ctor() by
1097 // overriding with custom code.
1098 [Obsolete("The method has been deprecated. It is not used by the system.")]
1099 protected virtual void Parse ()
1103 private void ParseUri (UriKind kind)
1105 Parse (kind, source);
1110 host = EscapeString (host, false, true, false);
1111 if (host.Length > 1 && host [0] != '[' && host [host.Length - 1] != ']') {
1112 // host name present (but not an IPv6 address)
1113 host = host.ToLower (CultureInfo.InvariantCulture);
1116 if (path.Length > 0) {
1117 path = EscapeString (path);
1122 string Unescape (string str)
1125 protected virtual string Unescape (string str)
1128 return Unescape (str, false);
1131 internal static string Unescape (string str, bool excludeSpecial)
1134 return String.Empty;
1135 StringBuilder s = new StringBuilder ();
1136 int len = str.Length;
1137 for (int i = 0; i < len; i++) {
1141 char x = HexUnescapeMultiByte (str, ref i, out surrogate);
1142 if (excludeSpecial && x == '#')
1144 else if (excludeSpecial && x == '%')
1146 else if (excludeSpecial && x == '?')
1150 if (surrogate != char.MinValue)
1151 s.Append (surrogate);
1157 return s.ToString ();
1163 private void ParseAsWindowsUNC (string uriString)
1165 scheme = UriSchemeFile;
1167 fragment = String.Empty;
1168 query = String.Empty;
1171 uriString = uriString.TrimStart (new char [] {'\\'});
1172 int pos = uriString.IndexOf ('\\');
1174 path = uriString.Substring (pos);
1175 host = uriString.Substring (0, pos);
1176 } else { // "\\\\server"
1178 path = String.Empty;
1180 path = path.Replace ("\\", "/");
1184 // Returns null on success, string with error on failure
1186 private string ParseAsWindowsAbsoluteFilePath (string uriString)
1188 if (uriString.Length > 2 && uriString [2] != '\\' && uriString [2] != '/')
1189 return "Relative file path is not allowed.";
1190 scheme = UriSchemeFile;
1191 host = String.Empty;
1193 path = uriString.Replace ("\\", "/");
1194 fragment = String.Empty;
1195 query = String.Empty;
1200 private void ParseAsUnixAbsoluteFilePath (string uriString)
1202 isUnixFilePath = true;
1203 scheme = UriSchemeFile;
1205 fragment = String.Empty;
1206 query = String.Empty;
1207 host = String.Empty;
1210 if (uriString.Length >= 2 && uriString [0] == '/' && uriString [1] == '/') {
1211 uriString = uriString.TrimStart (new char [] {'/'});
1212 // Now we don't regard //foo/bar as "foo" host.
1214 int pos = uriString.IndexOf ('/');
1216 path = '/' + uriString.Substring (pos + 1);
1217 host = uriString.Substring (0, pos);
1218 } else { // "///server"
1220 path = String.Empty;
1223 path = '/' + uriString;
1230 // This parse method will throw exceptions on failure
1232 private void Parse (UriKind kind, string uriString)
1234 if (uriString == null)
1235 throw new ArgumentNullException ("uriString");
1237 string s = ParseNoExceptions (kind, uriString);
1239 throw new UriFormatException (s);
1243 // This parse method will not throw exceptions on failure
1245 // Returns null on success, or a description of the error in the parsing
1247 private string ParseNoExceptions (UriKind kind, string uriString)
1252 // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1256 uriString = uriString.Trim();
1257 int len = uriString.Length;
1260 if (kind == UriKind.Relative || kind == UriKind.RelativeOrAbsolute){
1261 isAbsoluteUri = false;
1266 if (len <= 1 && (kind == UriKind.Absolute))
1267 return "Absolute URI is too short";
1272 // Identify Windows path, unix path, or standard URI.
1273 if (uriString [0] == '/' && Path.DirectorySeparatorChar == '/'){
1275 ParseAsUnixAbsoluteFilePath (uriString);
1277 isAbsoluteUri = false;
1279 if (kind == UriKind.Relative)
1280 isAbsoluteUri = false;
1283 } else if (uriString.Length >= 2 && uriString [0] == '\\' && uriString [1] == '\\') {
1285 ParseAsWindowsUNC (uriString);
1290 pos = uriString.IndexOf (':');
1292 return "Invalid URI: The format of the URI could not be determined.";
1293 } else if (pos < 0) {
1295 isAbsoluteUri = false;
1298 } else if (pos == 1) {
1299 if (!IsAlpha (uriString [0]))
1300 return "URI scheme must start with a letter.";
1301 // This means 'a:' == windows full path.
1302 string msg = ParseAsWindowsAbsoluteFilePath (uriString);
1309 scheme = uriString.Substring (0, pos).ToLower (CultureInfo.InvariantCulture);
1311 // Check scheme name characters as specified in RFC2396.
1312 // Note: different checks in 1.x and 2.0
1313 if (!CheckSchemeName (scheme))
1314 return Locale.GetText ("URI scheme must start with a letter and must consist of one of alphabet, digits, '+', '-' or '.' character.");
1316 // from here we're practically working on uriString.Substring(startpos,endpos-startpos)
1317 int startpos = pos + 1;
1318 int endpos = uriString.Length;
1321 pos = uriString.IndexOf ('#', startpos);
1322 if (!IsUnc && pos != -1) {
1324 fragment = uriString.Substring (pos);
1326 fragment = "#" + EscapeString (uriString.Substring (pos+1));
1332 pos = uriString.IndexOf ('?', startpos, endpos-startpos);
1334 query = uriString.Substring (pos, endpos-pos);
1337 query = EscapeString (query);
1341 if (IsPredefinedScheme (scheme) && scheme != UriSchemeMailto && scheme != UriSchemeNews && (
1342 (endpos-startpos < 2) ||
1343 (endpos-startpos >= 2 && uriString [startpos] == '/' && uriString [startpos+1] != '/')))
1344 return "Invalid URI: The Authority/Host could not be parsed.";
1347 bool startsWithSlashSlash = endpos-startpos >= 2 && uriString [startpos] == '/' && uriString [startpos+1] == '/';
1348 bool unixAbsPath = scheme == UriSchemeFile && startsWithSlashSlash && (endpos-startpos == 2 || uriString [startpos+2] == '/');
1349 bool windowsFilePath = false;
1350 if (startsWithSlashSlash) {
1351 if (kind == UriKind.Relative)
1352 return "Absolute URI when we expected a relative one";
1354 if (scheme != UriSchemeMailto && scheme != UriSchemeNews)
1357 if (scheme == UriSchemeFile) {
1358 int num_leading_slash = 2;
1359 for (int i = startpos; i < endpos; i++) {
1360 if (uriString [i] != '/')
1362 num_leading_slash++;
1364 if (num_leading_slash >= 4) {
1365 unixAbsPath = false;
1366 while (startpos < endpos && uriString[startpos] == '/') {
1369 } else if (num_leading_slash >= 3) {
1374 if (endpos - startpos > 1 && uriString [startpos + 1] == ':') {
1375 unixAbsPath = false;
1376 windowsFilePath = true;
1379 } else if (!IsPredefinedScheme (scheme)) {
1380 path = uriString.Substring(startpos, endpos-startpos);
1381 isOpaquePart = true;
1389 pos = uriString.IndexOf ('/', startpos, endpos-startpos);
1390 if (pos == -1 && windowsFilePath)
1391 pos = uriString.IndexOf ('\\', startpos, endpos-startpos);
1395 if ((scheme != Uri.UriSchemeMailto) &&
1397 (scheme != Uri.UriSchemeFile) &&
1399 (scheme != Uri.UriSchemeNews))
1402 path = uriString.Substring (pos, endpos-pos);
1410 pos = uriString.IndexOf ('@', startpos, endpos-startpos);
1412 userinfo = uriString.Substring (startpos, pos-startpos);
1421 pos = uriString.LastIndexOf (':', endpos-1, endpos-startpos);
1422 if (pos != -1 && pos != endpos - 1) {
1423 string portStr = uriString.Substring(pos + 1, endpos - (pos + 1));
1424 if (portStr.Length > 0 && portStr[portStr.Length - 1] != ']') {
1425 if (!Int32.TryParse (portStr, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) ||
1426 port < 0 || port > UInt16.MaxValue)
1427 return "Invalid URI: Invalid port number";
1431 port = GetDefaultPort (scheme);
1436 port = GetDefaultPort (scheme);
1441 uriString = uriString.Substring(startpos, endpos-startpos);
1445 path = Reduce ('/' + uriString);
1446 host = String.Empty;
1447 } else if (host.Length == 2 && host [1] == ':') {
1450 host = String.Empty;
1451 } else if (isUnixFilePath) {
1452 uriString = "//" + uriString;
1453 host = String.Empty;
1454 } else if (scheme == UriSchemeFile) {
1456 } else if (scheme == UriSchemeNews) {
1457 // no host for 'news', misinterpreted path
1458 if (host.Length > 0) {
1460 host = String.Empty;
1462 } else if (host.Length == 0 &&
1463 (scheme == UriSchemeHttp || scheme == UriSchemeGopher || scheme == UriSchemeNntp ||
1464 scheme == UriSchemeHttps || scheme == UriSchemeFtp)) {
1465 return "Invalid URI: The hostname could not be parsed";
1468 bool badhost = ((host.Length > 0) && (CheckHostName (host) == UriHostNameType.Unknown));
1469 if (!badhost && (host.Length > 1) && (host[0] == '[') && (host[host.Length - 1] == ']')) {
1470 IPv6Address ipv6addr;
1472 if (IPv6Address.TryParse (host, out ipv6addr))
1473 host = "[" + ipv6addr.ToString (true) + "]";
1477 if (badhost && (Parser is DefaultUriParser || Parser == null))
1478 return Locale.GetText ("Invalid URI: The hostname could not be parsed. (" + host + ")");
1480 UriFormatException ex = null;
1482 Parser.InitializeAndValidate (this, out ex);
1486 if ((scheme != Uri.UriSchemeMailto) &&
1487 (scheme != Uri.UriSchemeNews) &&
1488 (scheme != Uri.UriSchemeFile)) {
1489 path = Reduce (path);
1495 private static string Reduce (string path)
1497 // quick out, allocation-free, for a common case
1501 // replace '\', %5C ('\') and %2f ('/') into '/'
1502 // other escaped values seems to survive this step
1503 StringBuilder res = new StringBuilder();
1504 for (int i=0; i < path.Length; i++) {
1511 if (i < path.Length - 2) {
1512 char c1 = path [i + 1];
1513 char c2 = Char.ToUpper (path [i + 2]);
1514 if (((c1 == '2') && (c2 == 'F')) || ((c1 == '5') && (c2 == 'C'))) {
1529 path = res.ToString ();
1530 ArrayList result = new ArrayList ();
1532 for (int startpos = 0; startpos < path.Length; ) {
1533 int endpos = path.IndexOf('/', startpos);
1534 if (endpos == -1) endpos = path.Length;
1535 string current = path.Substring (startpos, endpos-startpos);
1536 startpos = endpos + 1;
1537 if (current.Length == 0 || current == "." )
1540 if (current == "..") {
1541 int resultCount = result.Count;
1542 // in 2.0 profile, skip leading ".." parts
1543 if (resultCount == 0) {
1547 result.RemoveAt (resultCount - 1);
1551 result.Add (current);
1554 if (result.Count == 0)
1558 if (path [0] == '/')
1562 foreach (string part in result) {
1571 if (path.EndsWith ("/"))
1574 return res.ToString();
1577 // A variant of HexUnescape() which can decode multi-byte escaped
1578 // sequences such as (e.g.) %E3%81%8B into a single character
1579 private static char HexUnescapeMultiByte (string pattern, ref int index, out char surrogate)
1581 surrogate = char.MinValue;
1583 if (pattern == null)
1584 throw new ArgumentException ("pattern");
1586 if (index < 0 || index >= pattern.Length)
1587 throw new ArgumentOutOfRangeException ("index");
1589 if (!IsHexEncoding (pattern, index))
1590 return pattern [index++];
1592 int orig_index = index++;
1593 int msb = FromHex (pattern [index++]);
1594 int lsb = FromHex (pattern [index++]);
1596 // We might be dealing with a multi-byte character:
1597 // The number of ones at the top-end of the first byte will tell us
1598 // how many bytes will make up this character.
1601 while ((msb_copy & 0x8) == 0x8) {
1606 // We might be dealing with a single-byte character:
1607 // If there was only 0 or 1 leading ones then we're not dealing
1608 // with a multi-byte character.
1610 return (char) ((msb << 4) | lsb);
1612 // Now that we know how many bytes *should* follow, we'll check them
1613 // to ensure we are dealing with a valid multi-byte character.
1614 byte [] chars = new byte [num_bytes];
1615 bool all_invalid = false;
1616 chars[0] = (byte) ((msb << 4) | lsb);
1618 for (int i = 1; i < num_bytes; i++) {
1619 if (!IsHexEncoding (pattern, index++)) {
1624 // All following bytes must be in the form 10xxxxxx
1625 int cur_msb = FromHex (pattern [index++]);
1626 if ((cur_msb & 0xc) != 0x8) {
1631 int cur_lsb = FromHex (pattern [index++]);
1632 chars[i] = (byte) ((cur_msb << 4) | cur_lsb);
1635 // If what looked like a multi-byte character is invalid, then we'll
1636 // just return the first byte as a single byte character.
1638 index = orig_index + 3;
1639 return (char) chars[0];
1642 // Otherwise, we're dealing with a valid multi-byte character.
1643 // We need to ignore the leading ones from the first byte:
1644 byte mask = (byte) 0xFF;
1645 mask >>= (num_bytes + 1);
1646 int result = chars[0] & mask;
1648 // The result will now be built up from the following bytes.
1649 for (int i = 1; i < num_bytes; i++) {
1650 // Ignore upper two bits
1652 result |= (chars[i] & 0x3F);
1655 if (result <= 0xFFFF) {
1656 return (char) result;
1658 // We need to handle this as a UTF16 surrogate (i.e. return
1661 surrogate = (char) ((result & 0x3FF) | 0xDC00);
1662 return (char) ((result >> 10) | 0xD800);
1666 private struct UriScheme
1668 public string scheme;
1669 public string delimiter;
1670 public int defaultPort;
1672 public UriScheme (string s, string d, int p)
1680 static UriScheme [] schemes = new UriScheme [] {
1681 new UriScheme (UriSchemeHttp, SchemeDelimiter, 80),
1682 new UriScheme (UriSchemeHttps, SchemeDelimiter, 443),
1683 new UriScheme (UriSchemeFtp, SchemeDelimiter, 21),
1684 new UriScheme (UriSchemeFile, SchemeDelimiter, -1),
1685 new UriScheme (UriSchemeMailto, ":", 25),
1686 new UriScheme (UriSchemeNews, ":", 119),
1687 new UriScheme (UriSchemeNntp, SchemeDelimiter, 119),
1688 new UriScheme (UriSchemeGopher, SchemeDelimiter, 70),
1691 internal static string GetSchemeDelimiter (string scheme)
1693 for (int i = 0; i < schemes.Length; i++)
1694 if (schemes [i].scheme == scheme)
1695 return schemes [i].delimiter;
1696 return Uri.SchemeDelimiter;
1699 internal static int GetDefaultPort (string scheme)
1701 UriParser parser = UriParser.GetParser (scheme);
1704 return parser.DefaultPort;
1707 private string GetOpaqueWiseSchemeDelimiter ()
1712 return GetSchemeDelimiter (scheme);
1716 protected virtual bool IsBadFileSystemCharacter (char ch)
1718 // It does not always overlap with InvalidPathChars.
1719 int chInt = (int) ch;
1720 if (chInt < 32 || (chInt < 64 && chInt > 57))
1739 protected static bool IsExcludedCharacter (char ch)
1741 if (ch <= 32 || ch >= 127)
1744 if (ch == '"' || ch == '#' || ch == '%' || ch == '<' ||
1745 ch == '>' || ch == '[' || ch == '\\' || ch == ']' ||
1746 ch == '^' || ch == '`' || ch == '{' || ch == '|' ||
1752 internal static bool MaybeUri (string s)
1754 int p = s.IndexOf (':');
1761 return IsPredefinedScheme (s.Substring (0, p));
1764 private static bool IsPredefinedScheme (string scheme)
1784 protected virtual bool IsReservedCharacter (char ch)
1786 if (ch == '$' || ch == '&' || ch == '+' || ch == ',' ||
1787 ch == '/' || ch == ':' || ch == ';' || ch == '=' ||
1794 private UriParser parser;
1796 private UriParser Parser {
1798 if (parser == null) {
1799 parser = UriParser.GetParser (Scheme);
1800 // no specific parser ? then use a default one
1802 parser = new DefaultUriParser ("*");
1806 set { parser = value; }
1809 public string GetComponents (UriComponents components, UriFormat format)
1811 return Parser.GetComponents (this, components, format);
1814 public bool IsBaseOf (Uri uri)
1816 return Parser.IsBaseOf (this, uri);
1819 public bool IsWellFormedOriginalString ()
1821 // funny, but it does not use the Parser's IsWellFormedOriginalString().
1822 // Also, it seems we need to *not* escape hex.
1823 return EscapeString (OriginalString, false, false, true) == OriginalString;
1828 private const int MaxUriLength = 32766;
1830 public static int Compare (Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType)
1832 if ((comparisonType < StringComparison.CurrentCulture) || (comparisonType > StringComparison.OrdinalIgnoreCase)) {
1833 string msg = Locale.GetText ("Invalid StringComparison value '{0}'", comparisonType);
1834 throw new ArgumentException ("comparisonType", msg);
1837 if ((uri1 == null) && (uri2 == null))
1840 string s1 = uri1.GetComponents (partsToCompare, compareFormat);
1841 string s2 = uri2.GetComponents (partsToCompare, compareFormat);
1842 return String.Compare (s1, s2, comparisonType);
1846 // The rules for EscapeDataString
1848 static bool NeedToEscapeDataChar (char b)
1850 return !((b >= 'A' && b <= 'Z') ||
1851 (b >= 'a' && b <= 'z') ||
1852 (b >= '0' && b <= '9') ||
1853 b == '_' || b == '~' || b == '!' || b == '\'' ||
1854 b == '(' || b == ')' || b == '*' || b == '-' || b == '.');
1857 public static string EscapeDataString (string stringToEscape)
1859 if (stringToEscape == null)
1860 throw new ArgumentNullException ("stringToEscape");
1862 if (stringToEscape.Length > MaxUriLength) {
1863 string msg = Locale.GetText ("Uri is longer than the maximum {0} characters.");
1864 throw new UriFormatException (msg);
1866 bool escape = false;
1867 foreach (char c in stringToEscape){
1868 if (NeedToEscapeDataChar (c)){
1874 return stringToEscape;
1877 StringBuilder sb = new StringBuilder ();
1878 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
1879 foreach (byte b in bytes){
1880 if (NeedToEscapeDataChar ((char) b))
1881 sb.Append (HexEscape ((char) b));
1883 sb.Append ((char) b);
1885 return sb.ToString ();
1889 // The rules for EscapeUriString
1891 static bool NeedToEscapeUriChar (char b)
1893 return !((b >= 'A' && b <= 'Z') ||
1894 (b >= 'a' && b <= 'z') ||
1895 (b >= '&' && b <= ';') ||
1896 b == '!' || b == '#' || b == '$' || b == '=' ||
1897 b == '?' || b == '@' || b == '_' || b == '~');
1900 public static string EscapeUriString (string stringToEscape)
1902 if (stringToEscape == null)
1903 throw new ArgumentNullException ("stringToEscape");
1905 if (stringToEscape.Length > MaxUriLength) {
1906 string msg = Locale.GetText ("Uri is longer than the maximum {0} characters.");
1907 throw new UriFormatException (msg);
1910 bool escape = false;
1911 foreach (char c in stringToEscape){
1912 if (NeedToEscapeUriChar (c)){
1918 return stringToEscape;
1920 StringBuilder sb = new StringBuilder ();
1921 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
1922 foreach (byte b in bytes){
1923 if (NeedToEscapeUriChar ((char) b))
1924 sb.Append (HexEscape ((char) b));
1926 sb.Append ((char) b);
1928 return sb.ToString ();
1931 public static bool IsWellFormedUriString (string uriString, UriKind uriKind)
1933 if (uriString == null)
1937 if (Uri.TryCreate (uriString, uriKind, out uri))
1938 return uri.IsWellFormedOriginalString ();
1942 public static bool TryCreate (string uriString, UriKind uriKind, out Uri result)
1946 Uri r = new Uri (uriString, uriKind, out success);
1955 // [MonoTODO ("rework code to avoid exception catching")]
1956 public static bool TryCreate (Uri baseUri, string relativeUri, out Uri result)
1959 // FIXME: this should call UriParser.Resolve
1960 result = new Uri (baseUri, relativeUri);
1962 } catch (UriFormatException) {
1968 //[MonoTODO ("rework code to avoid exception catching")]
1969 public static bool TryCreate (Uri baseUri, Uri relativeUri, out Uri result)
1972 // FIXME: this should call UriParser.Resolve
1973 result = new Uri (baseUri, relativeUri.OriginalString);
1975 } catch (UriFormatException) {
1981 public static string UnescapeDataString (string stringToUnescape)
1983 if (stringToUnescape == null)
1984 throw new ArgumentNullException ("stringToUnescape");
1986 if (stringToUnescape.IndexOf ('%') == -1 && stringToUnescape.IndexOf ('+') == -1)
1987 return stringToUnescape;
1989 StringBuilder output = new StringBuilder ();
1990 long len = stringToUnescape.Length;
1991 MemoryStream bytes = new MemoryStream ();
1994 for (int i = 0; i < len; i++) {
1995 if (stringToUnescape [i] == '%' && i + 2 < len && stringToUnescape [i + 1] != '%') {
1996 if (stringToUnescape [i + 1] == 'u' && i + 5 < len) {
1997 if (bytes.Length > 0) {
1998 output.Append (GetChars (bytes, Encoding.UTF8));
1999 bytes.SetLength (0);
2002 xchar = GetChar (stringToUnescape, i + 2, 4);
2004 output.Append ((char) xchar);
2008 output.Append ('%');
2011 else if ((xchar = GetChar (stringToUnescape, i + 1, 2)) != -1) {
2012 bytes.WriteByte ((byte) xchar);
2016 output.Append ('%');
2021 if (bytes.Length > 0) {
2022 output.Append (GetChars (bytes, Encoding.UTF8));
2023 bytes.SetLength (0);
2026 output.Append (stringToUnescape [i]);
2029 if (bytes.Length > 0) {
2030 output.Append (GetChars (bytes, Encoding.UTF8));
2034 return output.ToString ();
2037 private static int GetInt (byte b)
2040 if (c >= '0' && c <= '9')
2043 if (c >= 'a' && c <= 'f')
2044 return c - 'a' + 10;
2046 if (c >= 'A' && c <= 'F')
2047 return c - 'A' + 10;
2052 private static int GetChar (string str, int offset, int length)
2055 int end = length + offset;
2056 for (int i = offset; i < end; i++) {
2061 int current = GetInt ((byte) c);
2064 val = (val << 4) + current;
2070 private static char [] GetChars (MemoryStream b, Encoding e)
2072 return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
2076 private void EnsureAbsoluteUri ()
2079 throw new InvalidOperationException ("This operation is not supported for a relative URI.");