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 bool isUnixFilePath;
73 private string source;
74 private string scheme = String.Empty;
75 private string host = String.Empty;
76 private int port = -1;
77 private string path = String.Empty;
78 private string query = String.Empty;
79 private string fragment = String.Empty;
80 private string userinfo;
82 private bool isOpaquePart;
83 private bool isAbsoluteUri = true;
84 private long scope_id;
86 private List<string> segments;
88 private bool userEscaped;
89 private string cachedAbsoluteUri;
90 private string cachedToString;
91 private string cachedLocalPath;
92 private int cachedHashCode;
94 private static readonly string hexUpperChars = "0123456789ABCDEF";
95 private static readonly string [] Empty = new string [0];
96 private static bool isWin32 = (Path.DirectorySeparatorChar == '\\');
100 public static readonly string SchemeDelimiter = "://";
101 public static readonly string UriSchemeFile = "file";
102 public static readonly string UriSchemeFtp = "ftp";
103 public static readonly string UriSchemeGopher = "gopher";
104 public static readonly string UriSchemeHttp = "http";
105 public static readonly string UriSchemeHttps = "https";
106 public static readonly string UriSchemeMailto = "mailto";
107 public static readonly string UriSchemeNews = "news";
108 public static readonly string UriSchemeNntp = "nntp";
109 public static readonly string UriSchemeNetPipe = "net.pipe";
110 public static readonly string UriSchemeNetTcp = "net.tcp";
112 private static readonly string [] knownUriSchemes =
128 public Uri (string uriString) : this (uriString, false)
132 protected Uri (SerializationInfo serializationInfo, StreamingContext streamingContext)
134 string uri = serializationInfo.GetString ("AbsoluteUri");
135 if (uri.Length > 0) {
137 ParseUri(UriKind.Absolute);
139 uri = serializationInfo.GetString ("RelativeUri");
140 if (uri.Length > 0) {
142 ParseUri(UriKind.Relative);
144 throw new ArgumentException("Uri string was null or empty.");
149 public Uri (string uriString, UriKind uriKind)
155 case UriKind.Absolute:
157 throw new UriFormatException("Invalid URI: The format of the URI could not be "
160 case UriKind.Relative:
162 throw new UriFormatException("Invalid URI: The format of the URI could not be "
163 + "determined because the parameter 'uriString' represents an absolute URI.");
165 case UriKind.RelativeOrAbsolute:
168 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
169 throw new ArgumentException (msg);
174 // An exception-less constructor, returns success
175 // condition on the out parameter `success'.
177 Uri (string uriString, UriKind uriKind, out bool success)
179 if (uriString == null) {
184 if (uriKind != UriKind.RelativeOrAbsolute &&
185 uriKind != UriKind.Absolute &&
186 uriKind != UriKind.Relative) {
187 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
188 throw new ArgumentException (msg);
192 if (ParseNoExceptions (uriKind, uriString) != null)
198 case UriKind.Absolute:
202 case UriKind.Relative:
206 case UriKind.RelativeOrAbsolute:
215 public Uri (Uri baseUri, Uri relativeUri)
217 Merge (baseUri, relativeUri == null ? String.Empty : relativeUri.OriginalString);
218 // FIXME: this should call UriParser.Resolve
221 // note: doc says that dontEscape is always false but tests show otherwise
223 public Uri (string uriString, bool dontEscape)
225 userEscaped = dontEscape;
227 ParseUri (UriKind.Absolute);
229 throw new UriFormatException("Invalid URI: The format of the URI could not be "
230 + "determined: " + uriString);
233 public Uri (Uri baseUri, string relativeUri)
235 Merge (baseUri, relativeUri);
236 // FIXME: this should call UriParser.Resolve
239 [Obsolete ("dontEscape is always false")]
240 public Uri (Uri baseUri, string relativeUri, bool dontEscape)
242 userEscaped = dontEscape;
243 Merge (baseUri, relativeUri);
246 private void Merge (Uri baseUri, string relativeUri)
249 throw new ArgumentNullException ("baseUri");
250 if (!baseUri.IsAbsoluteUri)
251 throw new ArgumentOutOfRangeException ("baseUri");
252 if (relativeUri == null)
253 relativeUri = String.Empty;
255 // See RFC 2396 Par 5.2 and Appendix C
257 // Check Windows UNC (for // it is scheme/host separator)
258 if (relativeUri.Length >= 2 && relativeUri [0] == '\\' && relativeUri [1] == '\\') {
259 source = relativeUri;
260 ParseUri (UriKind.Absolute);
264 int pos = relativeUri.IndexOf (':');
267 int pos2 = relativeUri.IndexOfAny (new char [] {'/', '\\', '?'});
269 // pos2 < 0 ... e.g. mailto
270 // pos2 > pos ... to block ':' in query part
271 if (pos2 > pos || pos2 < 0) {
272 // in some cases, it is equivanent to new Uri (relativeUri, dontEscape):
273 // 1) when the URI scheme in the
274 // relative path is different from that
275 // of the baseUri, or
276 // 2) the URI scheme is non-standard
277 // ones (non-standard URIs are always
278 // treated as absolute here), or
279 // 3) the relative URI path is absolute.
280 if (String.CompareOrdinal (baseUri.Scheme, 0, relativeUri, 0, pos) != 0 ||
281 !IsPredefinedScheme (baseUri.Scheme) ||
282 (relativeUri.Length > pos + 1 && relativeUri [pos + 1] == '/')) {
284 if (Uri.TryCreate (relativeUri, UriKind.Absolute, out tmp)) {
285 source = relativeUri;
286 ParseUri (UriKind.Absolute);
288 } else if (pos == 1) {
289 // special case as this looks like a windows path
290 string msg = ParseAsWindowsAbsoluteFilePath (relativeUri);
292 throw new UriFormatException (msg);
294 // otherwise continue with 'full' relativeUri
297 relativeUri = relativeUri.Substring (pos + 1);
301 this.scheme = baseUri.scheme;
302 this.host = baseUri.host;
303 this.port = baseUri.port;
304 this.userinfo = baseUri.userinfo;
305 this.isUnc = baseUri.isUnc;
306 this.isUnixFilePath = baseUri.isUnixFilePath;
307 this.isOpaquePart = baseUri.isOpaquePart;
309 if (relativeUri.Length == 0) {
310 this.path = baseUri.path;
311 this.query = baseUri.query;
312 this.fragment = baseUri.fragment;
317 // Note that in relative constructor, file URI cannot handle '#' as a filename character, but just regarded as a fragment identifier.
318 string original_fragment = String.Empty;
319 pos = relativeUri.IndexOf ('#');
321 original_fragment = relativeUri.Substring (pos);
323 fragment = original_fragment;
325 fragment = "#" + EscapeString (relativeUri.Substring (pos+1));
326 relativeUri = pos == 0 ? String.Empty : relativeUri.Substring (0, pos);
329 bool consider_query = false;
332 pos = relativeUri.IndexOf ('?');
334 query = relativeUri.Substring (pos);
336 query = EscapeString (query);
337 #if !NET_4_0 && !MOBILE
338 consider_query = query.Length > 0;
340 relativeUri = pos == 0 ? String.Empty : relativeUri.Substring (0, pos);
341 } else if (relativeUri.Length == 0) {
342 // if there is no relative path then we keep the Query and Fragment from the absolute
343 query = baseUri.query;
346 if (relativeUri.Length > 0 && relativeUri [0] == '/') {
347 if (relativeUri.Length > 1 && relativeUri [1] == '/') {
348 source = scheme + ':' + relativeUri;
349 ParseUri (UriKind.Absolute);
354 path = EscapeString (path);
361 if ((relativeUri.Length > 0) || consider_query) {
362 pos = path.LastIndexOf ('/');
364 path = path.Substring (0, pos + 1);
367 if (relativeUri.Length == 0) {
368 // when merging URI the OriginalString is not quite original
369 source = GetLeftPart (UriPartial.Authority) + query + original_fragment;
379 pos = path.IndexOf ("./", startIndex);
383 path = path.Remove (0, 2);
384 else if (path [pos - 1] != '.')
385 path = path.Remove (pos, 2);
387 startIndex = pos + 1;
391 if (path.Length > 1 &&
392 path [path.Length - 1] == '.' &&
393 path [path.Length - 2] == '/')
394 path = path.Remove (path.Length - 1, 1);
399 pos = path.IndexOf ("/../", startIndex);
406 int pos2 = path.LastIndexOf ('/', pos - 1);
408 startIndex = pos + 1;
410 if (path.Substring (pos2 + 1, pos - pos2 - 1) != "..")
411 path = path.Remove (pos2 + 1, pos - pos2 + 3);
413 startIndex = pos + 1;
418 if (path.Length > 3 && path.EndsWith ("/..")) {
419 pos = path.LastIndexOf ('/', path.Length - 4);
421 if (path.Substring (pos + 1, path.Length - pos - 4) != "..")
422 path = path.Remove (pos + 1, path.Length - pos - 1);
426 while (path.StartsWith ("/../", StringComparison.Ordinal))
427 path = path.Substring (3);
430 path = EscapeString (path);
432 // when merging URI the OriginalString is not quite original
433 source = GetLeftPart (UriPartial.Authority) + path + query + original_fragment;
438 public string AbsolutePath {
440 EnsureAbsoluteUri ();
441 if (scheme == "mailto" || scheme == "file")
442 // faster (mailto) and special (file) cases
445 if (path.Length == 0) {
446 string start = scheme + SchemeDelimiter;
447 if (path.StartsWith (start, StringComparison.Ordinal))
456 public string AbsoluteUri {
458 EnsureAbsoluteUri ();
459 if (cachedAbsoluteUri == null) {
460 cachedAbsoluteUri = GetLeftPart (UriPartial.Path);
461 if (query.Length > 0)
462 cachedAbsoluteUri += query;
463 if (fragment.Length > 0)
464 cachedAbsoluteUri += fragment;
466 return cachedAbsoluteUri;
470 public string Authority {
472 EnsureAbsoluteUri ();
473 return (GetDefaultPort (Scheme) == port)
474 ? host : host + ":" + port;
478 public string Fragment {
480 EnsureAbsoluteUri ();
487 EnsureAbsoluteUri ();
492 public UriHostNameType HostNameType {
494 EnsureAbsoluteUri ();
495 UriHostNameType ret = CheckHostName (Host);
496 if (ret != UriHostNameType.Unknown)
499 if (scheme == "mailto")
500 return UriHostNameType.Basic;
501 return (IsFile) ? UriHostNameType.Basic : ret;
505 public bool IsDefaultPort {
507 EnsureAbsoluteUri ();
508 return GetDefaultPort (Scheme) == port;
514 EnsureAbsoluteUri ();
515 return (Scheme == UriSchemeFile);
519 public bool IsLoopback {
521 EnsureAbsoluteUri ();
523 if (Host.Length == 0) {
527 if (host == "loopback" || host == "localhost")
531 if (IPAddress.TryParse (host, out result))
532 if (IPAddress.Loopback.Equals (result))
536 if (IPv6Address.TryParse (host, out result6)){
537 if (IPv6Address.IsLoopback (result6))
546 // rule: This should be true only if
547 // - uri string starts from "\\", or
548 // - uri string starts from "//" (Samba way)
550 EnsureAbsoluteUri ();
555 private bool IsLocalIdenticalToAbsolutePath ()
560 if ((scheme == Uri.UriSchemeNews) || (scheme == Uri.UriSchemeNntp) || (scheme == Uri.UriSchemeFtp))
563 return IsWellFormedOriginalString ();
566 public string LocalPath {
568 EnsureAbsoluteUri ();
569 if (cachedLocalPath != null)
570 return cachedLocalPath;
572 if (IsLocalIdenticalToAbsolutePath ()) {
573 cachedLocalPath = Unescape (AbsolutePath);
574 return cachedLocalPath;
578 string p = Unescape (path);
579 bool windows = (path.Length > 3 && path [1] == ':' &&
580 (path [2] == '\\' || path [2] == '/'));
583 cachedLocalPath = p.Replace ('/', '\\');
587 // support *nix and W32 styles
588 if (path.Length > 1 && path [1] == ':')
589 cachedLocalPath = Unescape (path.Replace (Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));
591 // LAMESPEC: ok, now we cannot determine
592 // if such URI like "file://foo/bar" is
593 // Windows UNC or unix file path, so
594 // they should be handled differently.
595 else if (System.IO.Path.DirectorySeparatorChar == '\\') {
597 if (path.Length > 0) {
598 if ((path.Length > 1) || (path[0] != '/')) {
599 h += path.Replace ('/', '\\');
602 cachedLocalPath = "\\\\" + Unescape (h);
604 cachedLocalPath = Unescape (path);
606 if (cachedLocalPath.Length == 0)
607 cachedLocalPath = Path.DirectorySeparatorChar.ToString ();
608 return cachedLocalPath;
612 public string PathAndQuery {
614 EnsureAbsoluteUri ();
621 EnsureAbsoluteUri ();
626 public string Query {
628 EnsureAbsoluteUri ();
633 public string Scheme {
635 EnsureAbsoluteUri ();
640 public string [] Segments {
642 EnsureAbsoluteUri ();
644 // return a (pre-allocated) empty array
645 if (path.Length == 0)
647 // do not return the original array (since items can be changed)
648 if (segments != null)
649 return segments.ToArray ();
651 List<string> list = new List<string> ();
652 StringBuilder current = new StringBuilder ();
653 for (int i = 0; i < path.Length; i++) {
657 current.Append (path [i]);
658 list.Add (current.ToString ());
662 if ((i < path.Length - 2) && (path [i + 1] == '5' && path [i + 2] == 'C')) {
663 current.Append ("%5C");
664 list.Add (current.ToString ());
668 current.Append ('%');
672 current.Append (path [i]);
677 if (current.Length > 0)
678 list.Add (current.ToString ());
680 if (IsFile && (list.Count > 0)) {
681 string first = list [0];
682 if ((first.Length > 1) && (first [1] == ':')) {
683 list.Insert (0, "/");
687 return segments.ToArray ();
691 public bool UserEscaped {
692 get { return userEscaped; }
695 public string UserInfo {
697 EnsureAbsoluteUri ();
698 return userinfo == null ? String.Empty : userinfo;
702 public string DnsSafeHost {
704 EnsureAbsoluteUri ();
706 if (HostNameType == UriHostNameType.IPv6) {
707 host = Host.Substring (1, Host.Length - 2);
709 host += "%" + scope_id.ToString ();
711 return Unescape (host);
715 public bool IsAbsoluteUri {
716 get { return isAbsoluteUri; }
719 // LAMESPEC: source field is supplied in such case that this
720 // property makes sense. For such case that source field is
721 // not supplied (i.e. .ctor(Uri, string), this property
722 // makes no sense. To avoid silly regression it just returns
723 // ToString() value now. See bug #78374.
724 public string OriginalString {
725 get { return source != null ? source : ToString (); }
730 public static UriHostNameType CheckHostName (string name)
732 if (name == null || name.Length == 0)
733 return UriHostNameType.Unknown;
735 if (IsIPv4Address (name))
736 return UriHostNameType.IPv4;
738 if (IsDomainAddress (name))
739 return UriHostNameType.Dns;
742 if (IPv6Address.TryParse (name, out addr))
743 return UriHostNameType.IPv6;
745 return UriHostNameType.Unknown;
748 internal static bool IsIPv4Address (string name)
750 string [] captures = name.Split (new char [] {'.'});
751 if (captures.Length != 4)
754 for (int i = 0; i < 4; i++) {
757 length = captures [i].Length;
761 if (!UInt32.TryParse (captures [i], out number))
769 internal static bool IsDomainAddress (string name)
771 int len = name.Length;
774 for (int i = 0; i < len; i++) {
777 if (!Char.IsLetterOrDigit (c))
779 } else if (c == '.') {
780 // www..host.com is bad
781 if (i + 1 < len && name [i + 1] == '.')
785 } else if (!Char.IsLetterOrDigit (c) && c != '-' && c != '_') {
796 [Obsolete("This method does nothing, it has been obsoleted")]
797 protected virtual void Canonicalize ()
800 // This is flagged in the Microsoft documentation as used
801 // internally, no longer in use, and Obsolete.
805 [MonoTODO ("Find out what this should do")]
807 protected virtual void CheckSecurity ()
813 // defined in RFC3986 as = ALPHA *( ALPHA / DIGIT / "+" / "-" / ".")
814 public static bool CheckSchemeName (string schemeName)
816 if (schemeName == null || schemeName.Length == 0)
819 if (!IsAlpha (schemeName [0]))
822 int len = schemeName.Length;
823 for (int i = 1; i < len; i++) {
824 char c = schemeName [i];
825 if (!Char.IsDigit (c) && !IsAlpha (c) && c != '.' && c != '+' && c != '-')
832 private static bool IsAlpha (char c)
834 // as defined in rfc2234
835 // %x41-5A / %x61-7A (A-Z / a-z)
837 return (((i >= 0x41) && (i <= 0x5A)) || ((i >= 0x61) && (i <= 0x7A)));
840 public override bool Equals (object comparand)
842 if (comparand == null)
845 Uri uri = comparand as Uri;
846 if ((object) uri == null) {
847 string s = comparand as String;
851 if (!TryCreate (s, UriKind.RelativeOrAbsolute, out uri))
855 return InternalEquals (uri);
858 // Assumes: uri != null
859 bool InternalEquals (Uri uri)
861 if (this.isAbsoluteUri != uri.isAbsoluteUri)
863 if (!this.isAbsoluteUri)
864 return this.source == uri.source;
866 CultureInfo inv = CultureInfo.InvariantCulture;
867 return this.scheme.ToLower (inv) == uri.scheme.ToLower (inv)
868 && this.host.ToLower (inv) == uri.host.ToLower (inv)
869 && this.port == uri.port
870 && this.query == uri.query
871 && this.path == uri.path;
874 public static bool operator == (Uri uri1, Uri uri2)
876 return object.Equals (uri1, uri2);
879 public static bool operator != (Uri uri1, Uri uri2)
881 return !(uri1 == uri2);
884 public override int GetHashCode ()
886 if (cachedHashCode == 0) {
887 CultureInfo inv = CultureInfo.InvariantCulture;
889 cachedHashCode = scheme.ToLower (inv).GetHashCode ()
890 ^ host.ToLower (inv).GetHashCode ()
892 ^ query.GetHashCode ()
893 ^ path.GetHashCode ();
896 cachedHashCode = source.GetHashCode ();
899 return cachedHashCode;
902 public string GetLeftPart (UriPartial part)
904 EnsureAbsoluteUri ();
907 case UriPartial.Scheme :
908 return scheme + GetOpaqueWiseSchemeDelimiter ();
909 case UriPartial.Authority :
910 if ((scheme == Uri.UriSchemeMailto) || (scheme == Uri.UriSchemeNews))
913 StringBuilder s = new StringBuilder ();
915 s.Append (GetOpaqueWiseSchemeDelimiter ());
916 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
917 s.Append ('/'); // win32 file
918 if (userinfo != null)
919 s.Append (userinfo).Append ('@');
921 defaultPort = GetDefaultPort (scheme);
922 if ((port != -1) && (port != defaultPort))
923 s.Append (':').Append (port);
924 return s.ToString ();
925 case UriPartial.Path :
926 StringBuilder sb = new StringBuilder ();
928 sb.Append (GetOpaqueWiseSchemeDelimiter ());
929 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
930 sb.Append ('/'); // win32 file
931 if (userinfo != null)
932 sb.Append (userinfo).Append ('@');
934 defaultPort = GetDefaultPort (scheme);
935 if ((port != -1) && (port != defaultPort))
936 sb.Append (':').Append (port);
938 if (path.Length > 0) {
939 if (scheme == "mailto" || scheme == "news")
942 sb.Append (Reduce (path, CompactEscaped (scheme)));
944 return sb.ToString ();
949 public static int FromHex (char digit)
951 if ('0' <= digit && digit <= '9') {
952 return (int) (digit - '0');
955 if ('a' <= digit && digit <= 'f')
956 return (int) (digit - 'a' + 10);
958 if ('A' <= digit && digit <= 'F')
959 return (int) (digit - 'A' + 10);
961 throw new ArgumentException ("digit");
964 public static string HexEscape (char character)
966 if (character > 255) {
967 throw new ArgumentOutOfRangeException ("character");
970 return "%" + hexUpperChars [((character & 0xf0) >> 4)]
971 + hexUpperChars [((character & 0x0f))];
974 public static char HexUnescape (string pattern, ref int index)
977 throw new ArgumentException ("pattern");
979 if (index < 0 || index >= pattern.Length)
980 throw new ArgumentOutOfRangeException ("index");
982 if (!IsHexEncoding (pattern, index))
983 return pattern [index++];
986 int msb = FromHex (pattern [index++]);
987 int lsb = FromHex (pattern [index++]);
988 return (char) ((msb << 4) | lsb);
991 public static bool IsHexDigit (char character)
993 return (('0' <= character && character <= '9') ||
994 ('a' <= character && character <= 'f') ||
995 ('A' <= character && character <= 'F'));
998 public static bool IsHexEncoding (string pattern, int index)
1000 if ((index + 3) > pattern.Length)
1003 return ((pattern [index++] == '%') &&
1004 IsHexDigit (pattern [index++]) &&
1005 IsHexDigit (pattern [index]));
1009 // Implemented by copying most of the MakeRelative code
1011 public Uri MakeRelativeUri (Uri uri)
1015 throw new ArgumentNullException ("uri");
1017 if (Host != uri.Host || Scheme != uri.Scheme)
1020 string result = String.Empty;
1021 if (this.path != uri.path){
1022 string [] segments = this.Segments;
1023 string [] segments2 = uri.Segments;
1026 int max = Math.Min (segments.Length, segments2.Length);
1027 for (; k < max; k++)
1028 if (segments [k] != segments2 [k])
1031 for (int i = k; i < segments.Length && segments [i].EndsWith ("/"); i++)
1033 for (int i = k; i < segments2.Length; i++)
1034 result += segments2 [i];
1036 if (result == string.Empty)
1039 uri.AppendQueryAndFragment (ref result);
1041 return new Uri (result, UriKind.Relative);
1044 [Obsolete ("Use MakeRelativeUri(Uri uri) instead.")]
1045 public string MakeRelative (Uri toUri)
1047 if ((this.Scheme != toUri.Scheme) ||
1048 (this.Authority != toUri.Authority))
1049 return toUri.ToString ();
1051 string result = String.Empty;
1052 if (this.path != toUri.path){
1053 string [] segments = this.Segments;
1054 string [] segments2 = toUri.Segments;
1056 int max = Math.Min (segments.Length, segments2.Length);
1057 for (; k < max; k++)
1058 if (segments [k] != segments2 [k])
1061 for (int i = k + 1; i < segments.Length; i++)
1063 for (int i = k; i < segments2.Length; i++)
1064 result += segments2 [i];
1067 // Important: MakeRelative does not append fragment or query.
1072 void AppendQueryAndFragment (ref string result)
1074 if (query.Length > 0) {
1075 string q = query [0] == '?' ? '?' + Unescape (query.Substring (1), true, false) : Unescape (query, false);
1078 if (fragment.Length > 0)
1079 result += Unescape (fragment, true, false);
1082 public override string ToString ()
1084 if (cachedToString != null)
1085 return cachedToString;
1087 if (isAbsoluteUri) {
1088 cachedToString = Unescape (GetLeftPart (UriPartial.Path), true);
1089 AppendQueryAndFragment (ref cachedToString);
1091 // Everything is contained in path in this case.
1092 cachedToString = path;
1095 return cachedToString;
1098 protected void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
1100 if (this.isAbsoluteUri) {
1101 serializationInfo.AddValue ("AbsoluteUri", this.AbsoluteUri);
1103 serializationInfo.AddValue("AbsoluteUri", String.Empty);
1104 serializationInfo.AddValue("RelativeUri", this.OriginalString);
1108 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
1110 GetObjectData (info, context);
1117 protected virtual void Escape ()
1119 path = EscapeString (path);
1123 protected static string EscapeString (string str)
1125 return EscapeString (str, Uri.EscapeCommonHexBrackets);
1128 private const string EscapeCommon = "<>%\"{}|\\^`";
1129 private const string EscapeReserved = ";/?:@&=+$,";
1130 private const string EscapeFragment = "#";
1131 private const string EscapeBrackets = "[]";
1133 private const string EscapeNews = EscapeCommon + EscapeBrackets + "?";
1134 private const string EscapeCommonHex = EscapeCommon + EscapeFragment;
1135 private const string EscapeCommonBrackets = EscapeCommon + EscapeBrackets;
1136 internal const string EscapeCommonHexBrackets = EscapeCommon + EscapeFragment + EscapeBrackets;
1137 internal const string EscapeCommonHexBracketsQuery = EscapeCommonHexBrackets + "?";
1139 internal static string EscapeString (string str, string escape)
1141 return EscapeString (str, escape, true);
1144 internal static string EscapeString (string str, string escape, bool nonAsciiEscape)
1146 if (String.IsNullOrEmpty (str))
1147 return String.Empty;
1149 StringBuilder s = new StringBuilder ();
1150 int len = str.Length;
1151 for (int i = 0; i < len; i++) {
1152 // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
1153 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
1154 // control = <US-ASCII coded characters 00-1F and 7F hexadecimal>
1155 // space = <US-ASCII coded character 20 hexadecimal>
1156 // delims = "<" | ">" | "#" | "%" | <">
1157 // unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
1159 // check for escape code already placed in str,
1160 // i.e. for encoding that follows the pattern
1161 // "%hexhex" in a string, where "hex" is a digit from 0-9
1162 // or a letter from A-F (case-insensitive).
1163 if (IsHexEncoding (str,i)) {
1164 // if ,yes , copy it as is
1165 s.Append(str.Substring (i, 3));
1171 bool outside_limited_ascii = ((c <= 0x20) || (c >= 0x7f));
1172 bool needs_escape = (escape.IndexOf (c) != -1);
1173 if (nonAsciiEscape && outside_limited_ascii) {
1174 byte [] data = Encoding.UTF8.GetBytes (new char [] { c });
1175 int length = data.Length;
1176 for (int j = 0; j < length; j++) {
1177 c = (char) data [j];
1178 if (needs_escape || nonAsciiEscape)
1179 s.Append (HexEscape (c));
1183 } else if (needs_escape) {
1184 s.Append (HexEscape (c));
1190 return s.ToString ();
1193 // On .NET 1.x, this method is called from .ctor(). When overriden, we
1194 // can avoid the "absolute uri" constraints of the .ctor() by
1195 // overriding with custom code.
1196 [Obsolete("The method has been deprecated. It is not used by the system.")]
1197 protected virtual void Parse ()
1201 private void ParseUri (UriKind kind)
1203 Parse (kind, source);
1208 // non-ascii characters are not escaped for the host name
1209 host = EscapeString (host, EscapeCommonHex, false);
1210 if (host.Length > 1 && host [0] != '[' && host [host.Length - 1] != ']') {
1211 // host name present (but not an IPv6 address)
1212 host = host.ToLower (CultureInfo.InvariantCulture);
1215 if (isAbsoluteUri && (path.Length > 0))
1216 path = EscapeString (path);
1220 protected virtual string Unescape (string path)
1222 return Unescape (path, false, false);
1225 internal static string Unescape (string str, bool excludeSpecial)
1227 return Unescape (str, excludeSpecial, excludeSpecial);
1230 internal static string Unescape (string str, bool excludeSpecial, bool excludeBackslash)
1232 if (String.IsNullOrEmpty (str))
1233 return String.Empty;
1235 StringBuilder s = new StringBuilder ();
1236 int len = str.Length;
1237 for (int i = 0; i < len; i++) {
1241 char x = HexUnescapeMultiByte (str, ref i, out surrogate);
1242 if (excludeSpecial && x == '#')
1244 else if (excludeSpecial && x == '%')
1246 else if (excludeSpecial && x == '?')
1248 else if (excludeBackslash && x == '\\')
1252 if (surrogate != char.MinValue)
1253 s.Append (surrogate);
1259 return s.ToString ();
1265 private void ParseAsWindowsUNC (string uriString)
1267 scheme = UriSchemeFile;
1269 fragment = String.Empty;
1270 query = String.Empty;
1273 uriString = uriString.TrimStart (new char [] {'\\'});
1274 int pos = uriString.IndexOf ('\\');
1276 path = uriString.Substring (pos);
1277 host = uriString.Substring (0, pos);
1278 } else { // "\\\\server"
1280 path = String.Empty;
1282 path = path.Replace ("\\", "/");
1286 // Returns null on success, string with error on failure
1288 private string ParseAsWindowsAbsoluteFilePath (string uriString)
1290 if (uriString.Length > 2 && uriString [2] != '\\' && uriString [2] != '/')
1291 return "Relative file path is not allowed.";
1292 scheme = UriSchemeFile;
1293 host = String.Empty;
1295 path = uriString.Replace ("\\", "/");
1296 fragment = String.Empty;
1297 query = String.Empty;
1302 private void ParseAsUnixAbsoluteFilePath (string uriString)
1304 isUnixFilePath = true;
1305 scheme = UriSchemeFile;
1307 fragment = String.Empty;
1308 query = String.Empty;
1309 host = String.Empty;
1312 if (uriString.Length >= 2 && uriString [0] == '/' && uriString [1] == '/') {
1313 uriString = uriString.TrimStart (new char [] {'/'});
1314 // Now we don't regard //foo/bar as "foo" host.
1316 int pos = uriString.IndexOf ('/');
1318 path = '/' + uriString.Substring (pos + 1);
1319 host = uriString.Substring (0, pos);
1320 } else { // "///server"
1322 path = String.Empty;
1325 path = '/' + uriString;
1332 // This parse method will throw exceptions on failure
1334 private void Parse (UriKind kind, string uriString)
1336 if (uriString == null)
1337 throw new ArgumentNullException ("uriString");
1339 string s = ParseNoExceptions (kind, uriString);
1341 throw new UriFormatException (s);
1344 private bool SupportsQuery ()
1346 return ((scheme != Uri.UriSchemeNntp) && (scheme != Uri.UriSchemeFtp) && (scheme != Uri.UriSchemeFile));
1350 // This parse method will not throw exceptions on failure
1352 // Returns null on success, or a description of the error in the parsing
1354 private string ParseNoExceptions (UriKind kind, string uriString)
1359 // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1363 uriString = uriString.Trim();
1364 int len = uriString.Length;
1367 if (kind == UriKind.Relative || kind == UriKind.RelativeOrAbsolute){
1368 isAbsoluteUri = false;
1373 if (len <= 1 && (kind == UriKind.Absolute))
1374 return "Absolute URI is too short";
1379 // Identify Windows path, unix path, or standard URI.
1380 if (uriString [0] == '/' && Path.DirectorySeparatorChar == '/'){
1382 ParseAsUnixAbsoluteFilePath (uriString);
1383 if (kind == UriKind.Relative)
1384 isAbsoluteUri = false;
1386 } else if (uriString.Length >= 2 && uriString [0] == '\\' && uriString [1] == '\\') {
1388 ParseAsWindowsUNC (uriString);
1393 pos = uriString.IndexOf (':');
1395 if (kind == UriKind.Absolute)
1396 return "Invalid URI: The format of the URI could not be determined.";
1397 isAbsoluteUri = false;
1400 } else if (pos < 0) {
1402 isAbsoluteUri = false;
1405 } else if (pos == 1) {
1406 if (!IsAlpha (uriString [0])) {
1407 if (kind == UriKind.Absolute)
1408 return "Invalid URI: The URI scheme is not valid.";
1409 isAbsoluteUri = false;
1413 // This means 'a:' == windows full path.
1414 string msg = ParseAsWindowsAbsoluteFilePath (uriString);
1421 scheme = uriString.Substring (0, pos).ToLower (CultureInfo.InvariantCulture);
1423 // Check scheme name characters as specified in RFC2396.
1424 // Note: different checks in 1.x and 2.0
1425 if (!CheckSchemeName (scheme)) {
1426 if (kind == UriKind.Absolute)
1427 return "Invalid URI: The URI scheme is not valid.";
1428 isAbsoluteUri = false;
1433 scheme = TryGetKnownUriSchemeInstance (scheme);
1435 // from here we're practically working on uriString.Substring(startpos,endpos-startpos)
1436 int startpos = pos + 1;
1437 int endpos = uriString.Length;
1440 pos = uriString.IndexOf ('#', startpos);
1441 if (!IsUnc && pos != -1) {
1443 fragment = uriString.Substring (pos);
1445 fragment = "#" + EscapeString (uriString.Substring (pos+1));
1450 // special case: there is no query part for 'news'
1451 if (scheme == Uri.UriSchemeNews) {
1452 pos = scheme.Length + 1;
1453 path = EscapeString (uriString.Substring (pos, endpos - pos), EscapeNews);
1457 // special case: there is no query part for 'nntp', 'file' and 'ftp' but there is an host, port, user...
1458 if (SupportsQuery ()) {
1460 pos = uriString.IndexOf ('?', startpos, endpos-startpos);
1462 query = uriString.Substring (pos, endpos-pos);
1465 query = EscapeString (query);
1470 if (IsPredefinedScheme (scheme) && scheme != UriSchemeMailto && (
1471 (endpos-startpos < 2) ||
1472 (endpos-startpos >= 2 && uriString [startpos] == '/' && uriString [startpos+1] != '/')))
1473 return "Invalid URI: The Authority/Host could not be parsed.";
1476 bool startsWithSlashSlash = endpos-startpos >= 2 && uriString [startpos] == '/' && uriString [startpos+1] == '/';
1477 bool unixAbsPath = scheme == UriSchemeFile && startsWithSlashSlash && (endpos-startpos == 2 || uriString [startpos+2] == '/');
1478 bool windowsFilePath = false;
1479 if (startsWithSlashSlash) {
1480 if (kind == UriKind.Relative)
1481 return "Absolute URI when we expected a relative one";
1483 if (scheme != UriSchemeMailto)
1486 if (scheme == UriSchemeFile) {
1487 int num_leading_slash = 2;
1488 for (int i = startpos; i < endpos; i++) {
1489 if (uriString [i] != '/')
1491 num_leading_slash++;
1493 if (num_leading_slash >= 4) {
1494 unixAbsPath = false;
1495 while (startpos < endpos && uriString[startpos] == '/') {
1498 } else if (num_leading_slash >= 3) {
1503 if (endpos - startpos > 1 && uriString [startpos + 1] == ':') {
1504 unixAbsPath = false;
1505 windowsFilePath = true;
1508 } else if (!IsPredefinedScheme (scheme)) {
1509 path = uriString.Substring(startpos, endpos-startpos);
1510 isOpaquePart = true;
1518 pos = uriString.IndexOf ('/', startpos, endpos - startpos);
1519 if (pos == -1 && windowsFilePath)
1520 pos = uriString.IndexOf ('\\', startpos, endpos - startpos);
1523 path = uriString.Substring (pos, endpos - pos);
1524 if (!SupportsQuery ()) {
1525 if (scheme != Uri.UriSchemeNntp)
1526 path = path.Replace ('\\', '/');
1527 path = EscapeString (path, EscapeNews);
1531 if (scheme != Uri.UriSchemeMailto)
1539 pos = uriString.IndexOf ('@', startpos, endpos-startpos);
1541 // supplying username / password on a file URI is not supported
1542 if (scheme == UriSchemeFile)
1543 return "Invalid host";
1544 userinfo = uriString.Substring (startpos, pos-startpos);
1549 bool valid_port = true;
1554 pos = uriString.LastIndexOf (':', endpos-1, endpos-startpos);
1555 if (pos != -1 && pos != endpos - 1) {
1556 string portStr = uriString.Substring(pos + 1, endpos - (pos + 1));
1557 if (portStr.Length > 0 && portStr[portStr.Length - 1] != ']') {
1558 if (!Int32.TryParse (portStr, NumberStyles.None, CultureInfo.InvariantCulture, out port) ||
1559 port < 0 || port > UInt16.MaxValue)
1560 valid_port = false; // delay reporting
1565 port = GetDefaultPort (scheme);
1568 } else if (!IsFile) {
1569 // if no port is specified by a colon ':' is present then we must ignore it
1570 // since it would be part of the host name and, as such, would be invalid
1571 if (pos == endpos - 1)
1575 port = GetDefaultPort (scheme);
1579 uriString = uriString.Substring(startpos, endpos-startpos);
1583 path = Reduce ('/' + uriString, true);
1584 host = String.Empty;
1585 } else if (host.Length == 2 && host [1] == ':') {
1586 if (scheme != UriSchemeFile) {
1587 host = host [0].ToString ();
1591 host = String.Empty;
1593 } else if (isUnixFilePath) {
1594 uriString = "//" + uriString;
1595 host = String.Empty;
1596 } else if (scheme == UriSchemeFile) {
1597 // under Windows all file:// URI are considered UNC, which is not the case other MacOS (e.g. Silverlight)
1599 } else if (host.Length == 0 &&
1600 (scheme == UriSchemeHttp || scheme == UriSchemeGopher || scheme == UriSchemeNntp ||
1601 scheme == UriSchemeHttps || scheme == UriSchemeFtp)) {
1602 return "Invalid URI: The Authority/Host could not be parsed.";
1605 if (host.Length > 0) {
1606 switch (CheckHostName (host)) {
1607 case UriHostNameType.Unknown:
1608 if ((host [0] == ':') || (host [0] == '@'))
1609 return "Invalid URI: The hostname could not be parsed.";
1610 if (host.IndexOf (':') != -1)
1611 return "Invalid URI: Invalid port specified.";
1612 if (Parser is DefaultUriParser || Parser == null)
1613 return "Invalid URI: The hostname could not be parsed.";
1615 case UriHostNameType.IPv6:
1616 IPv6Address ipv6addr;
1617 if (IPv6Address.TryParse (host, out ipv6addr)) {
1618 host = "[" + ipv6addr.ToString (true) + "]";
1619 scope_id = ipv6addr.ScopeId;
1624 // delayed reporting (to throw the expected exception in the right order)
1626 return "Invalid URI: Invalid port number";
1628 UriFormatException ex = null;
1630 Parser.InitializeAndValidate (this, out ex);
1634 if ((scheme != Uri.UriSchemeMailto) && (scheme != Uri.UriSchemeFile)) {
1635 path = Reduce (path, CompactEscaped (scheme));
1641 private static string TryGetKnownUriSchemeInstance (string scheme)
1643 foreach (string knownScheme in knownUriSchemes) {
1644 if (knownScheme == scheme)
1651 private static bool CompactEscaped (string scheme)
1653 if (scheme == null || scheme.Length < 4)
1656 char first = scheme [0];
1658 return scheme == "http" || scheme == "https";
1659 } else if (first == 'f' && scheme == "file"){
1661 } else if (first == 'n')
1662 return scheme == "net.pipe" || scheme == "net.tcp";
1667 // replace '\', %5C ('\') and %2f ('/') into '/'
1668 // replace %2e ('.') into '.'
1669 private static string NormalizePath (string path)
1671 StringBuilder res = new StringBuilder ();
1672 for (int i = 0; i < path.Length; i++) {
1679 if (i < path.Length - 2) {
1680 char c1 = path [i + 1];
1681 char c2 = Char.ToUpper (path [i + 2]);
1682 if ((c1 == '2') && (c2 == 'E')) {
1685 } else if (((c1 == '2') && (c2 == 'F')) || ((c1 == '5') && (c2 == 'C'))) {
1694 return res.ToString ();
1697 // This is called "compacting" in the MSDN documentation
1698 private static string Reduce (string path, bool compact_escaped)
1700 // quick out, allocation-free, for a common case
1704 if (compact_escaped && (path.IndexOf ('%') != -1)) {
1705 // replace '\', %2f, %5c with '/' and replace %2e with '.'
1706 // other escaped values seems to survive this step
1707 path = NormalizePath (path);
1709 // (always) replace '\' with '/'
1710 path = path.Replace ('\\', '/');
1713 List<string> result = new List<string> ();
1716 for (int startpos = 0; startpos < path.Length; ) {
1717 int endpos = path.IndexOf ('/', startpos);
1719 endpos = path.Length;
1720 string current = path.Substring (startpos, endpos-startpos);
1721 startpos = endpos + 1;
1722 if ((begin && current.Length == 0) || current == "." ) {
1728 if (current == "..") {
1729 int resultCount = result.Count;
1730 // in 2.0 profile, skip leading ".." parts
1731 if (resultCount == 0) {
1735 result.RemoveAt (resultCount - 1);
1739 result.Add (current);
1742 if (result.Count == 0)
1745 StringBuilder res = new StringBuilder ();
1747 if (path [0] == '/')
1751 foreach (string part in result) {
1760 if (path [path.Length - 1] == '/')
1763 return res.ToString();
1766 // A variant of HexUnescape() which can decode multi-byte escaped
1767 // sequences such as (e.g.) %E3%81%8B into a single character
1768 private static char HexUnescapeMultiByte (string pattern, ref int index, out char surrogate)
1770 surrogate = char.MinValue;
1772 if (pattern == null)
1773 throw new ArgumentException ("pattern");
1775 if (index < 0 || index >= pattern.Length)
1776 throw new ArgumentOutOfRangeException ("index");
1778 if (!IsHexEncoding (pattern, index))
1779 return pattern [index++];
1781 int orig_index = index++;
1782 int msb = FromHex (pattern [index++]);
1783 int lsb = FromHex (pattern [index++]);
1785 // We might be dealing with a multi-byte character:
1786 // The number of ones at the top-end of the first byte will tell us
1787 // how many bytes will make up this character.
1790 while ((msb_copy & 0x8) == 0x8) {
1795 // We might be dealing with a single-byte character:
1796 // If there was only 0 or 1 leading ones then we're not dealing
1797 // with a multi-byte character.
1799 return (char) ((msb << 4) | lsb);
1801 // Now that we know how many bytes *should* follow, we'll check them
1802 // to ensure we are dealing with a valid multi-byte character.
1803 byte [] chars = new byte [num_bytes];
1804 bool all_invalid = false;
1805 chars[0] = (byte) ((msb << 4) | lsb);
1807 for (int i = 1; i < num_bytes; i++) {
1808 if (!IsHexEncoding (pattern, index++)) {
1813 // All following bytes must be in the form 10xxxxxx
1814 int cur_msb = FromHex (pattern [index++]);
1815 if ((cur_msb & 0xc) != 0x8) {
1820 int cur_lsb = FromHex (pattern [index++]);
1821 chars[i] = (byte) ((cur_msb << 4) | cur_lsb);
1824 // If what looked like a multi-byte character is invalid, then we'll
1825 // just return the first byte as a single byte character.
1827 index = orig_index + 3;
1828 return (char) chars[0];
1831 // Otherwise, we're dealing with a valid multi-byte character.
1832 // We need to ignore the leading ones from the first byte:
1833 byte mask = (byte) 0xFF;
1834 mask >>= (num_bytes + 1);
1835 int result = chars[0] & mask;
1837 // The result will now be built up from the following bytes.
1838 for (int i = 1; i < num_bytes; i++) {
1839 // Ignore upper two bits
1841 result |= (chars[i] & 0x3F);
1844 if (result <= 0xFFFF) {
1845 return (char) result;
1847 // We need to handle this as a UTF16 surrogate (i.e. return
1850 surrogate = (char) ((result & 0x3FF) | 0xDC00);
1851 return (char) ((result >> 10) | 0xD800);
1855 private struct UriScheme
1857 public string scheme;
1858 public string delimiter;
1859 public int defaultPort;
1861 public UriScheme (string s, string d, int p)
1869 static UriScheme [] schemes = new UriScheme [] {
1870 new UriScheme (UriSchemeHttp, SchemeDelimiter, 80),
1871 new UriScheme (UriSchemeHttps, SchemeDelimiter, 443),
1872 new UriScheme (UriSchemeFtp, SchemeDelimiter, 21),
1873 new UriScheme (UriSchemeFile, SchemeDelimiter, -1),
1874 new UriScheme (UriSchemeMailto, ":", 25),
1875 new UriScheme (UriSchemeNews, ":", 119),
1876 new UriScheme (UriSchemeNntp, SchemeDelimiter, 119),
1877 new UriScheme (UriSchemeGopher, SchemeDelimiter, 70),
1880 internal static string GetSchemeDelimiter (string scheme)
1882 for (int i = 0; i < schemes.Length; i++)
1883 if (schemes [i].scheme == scheme)
1884 return schemes [i].delimiter;
1885 return Uri.SchemeDelimiter;
1888 internal static int GetDefaultPort (string scheme)
1890 UriParser parser = UriParser.GetParser (scheme);
1893 return parser.DefaultPort;
1896 private string GetOpaqueWiseSchemeDelimiter ()
1901 return GetSchemeDelimiter (scheme);
1905 protected virtual bool IsBadFileSystemCharacter (char character)
1907 // It does not always overlap with InvalidPathChars.
1908 int chInt = (int) character;
1909 if (chInt < 32 || (chInt < 64 && chInt > 57))
1928 protected static bool IsExcludedCharacter (char character)
1930 if (character <= 32 || character >= 127)
1933 if (character == '"' || character == '#' || character == '%' || character == '<' ||
1934 character == '>' || character == '[' || character == '\\' || character == ']' ||
1935 character == '^' || character == '`' || character == '{' || character == '|' ||
1941 internal static bool MaybeUri (string s)
1943 int p = s.IndexOf (':');
1950 return IsPredefinedScheme (s.Substring (0, p));
1954 // Using a simple block of if's is twice as slow as the compiler generated
1955 // switch statement. But using this tuned code is faster than the
1956 // compiler generated code, with a million loops on x86-64:
1958 // With "http": .10 vs .51 (first check)
1959 // with "https": .16 vs .51 (second check)
1960 // with "foo": .22 vs .31 (never found)
1961 // with "mailto": .12 vs .51 (last check)
1964 private static bool IsPredefinedScheme (string scheme)
1966 if (scheme == null || scheme.Length < 3)
1969 char c = scheme [0];
1971 return (scheme == "http" || scheme == "https");
1973 return (scheme == "file" || scheme == "ftp");
1978 return (scheme == "news" || scheme == "net.pipe" || scheme == "net.tcp");
1979 if (scheme == "nntp")
1983 if ((c == 'g' && scheme == "gopher") || (c == 'm' && scheme == "mailto"))
1990 protected virtual bool IsReservedCharacter (char character)
1992 if (character == '$' || character == '&' || character == '+' || character == ',' ||
1993 character == '/' || character == ':' || character == ';' || character == '=' ||
2000 private UriParser parser;
2002 private UriParser Parser {
2004 if (parser == null) {
2005 parser = UriParser.GetParser (Scheme);
2006 // no specific parser ? then use a default one
2008 parser = new DefaultUriParser ("*");
2012 set { parser = value; }
2015 public string GetComponents (UriComponents components, UriFormat format)
2017 return Parser.GetComponents (this, components, format);
2020 public bool IsBaseOf (Uri uri)
2024 throw new ArgumentNullException ("uri");
2026 return Parser.IsBaseOf (this, uri);
2029 public bool IsWellFormedOriginalString ()
2031 // funny, but it does not use the Parser's IsWellFormedOriginalString().
2032 // Also, it seems we need to *not* escape hex.
2033 return EscapeString (OriginalString, EscapeCommonBrackets) == OriginalString;
2038 private const int MaxUriLength = 32766;
2040 public static int Compare (Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType)
2042 if ((comparisonType < StringComparison.CurrentCulture) || (comparisonType > StringComparison.OrdinalIgnoreCase)) {
2043 string msg = Locale.GetText ("Invalid StringComparison value '{0}'", comparisonType);
2044 throw new ArgumentException ("comparisonType", msg);
2047 if ((uri1 == null) && (uri2 == null))
2050 string s1 = uri1.GetComponents (partsToCompare, compareFormat);
2051 string s2 = uri2.GetComponents (partsToCompare, compareFormat);
2052 return String.Compare (s1, s2, comparisonType);
2056 // The rules for EscapeDataString
2058 static bool NeedToEscapeDataChar (char b)
2061 // .NET 4.0 follows RFC 3986 Unreserved Characters
2062 return !((b >= 'A' && b <= 'Z') ||
2063 (b >= 'a' && b <= 'z') ||
2064 (b >= '0' && b <= '9') ||
2065 b == '-' || b == '.' || b == '_' || b == '~');
2067 return !((b >= 'A' && b <= 'Z') ||
2068 (b >= 'a' && b <= 'z') ||
2069 (b >= '0' && b <= '9') ||
2070 b == '_' || b == '~' || b == '!' || b == '\'' ||
2071 b == '(' || b == ')' || b == '*' || b == '-' || b == '.');
2075 public static string EscapeDataString (string stringToEscape)
2077 if (stringToEscape == null)
2078 throw new ArgumentNullException ("stringToEscape");
2080 if (stringToEscape.Length > MaxUriLength) {
2081 throw new UriFormatException (string.Format ("Uri is longer than the maximum {0} characters.", MaxUriLength));
2084 bool escape = false;
2085 foreach (char c in stringToEscape){
2086 if (NeedToEscapeDataChar (c)){
2092 return stringToEscape;
2095 StringBuilder sb = new StringBuilder ();
2096 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
2097 foreach (byte b in bytes){
2098 if (NeedToEscapeDataChar ((char) b))
2099 sb.Append (HexEscape ((char) b));
2101 sb.Append ((char) b);
2103 return sb.ToString ();
2107 // The rules for EscapeUriString
2109 static bool NeedToEscapeUriChar (char b)
2111 if ((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '&' && b <= ';'))
2124 // .NET 4.0 follows RFC 3986
2134 public static string EscapeUriString (string stringToEscape)
2136 if (stringToEscape == null)
2137 throw new ArgumentNullException ("stringToEscape");
2139 if (stringToEscape.Length > MaxUriLength) {
2140 throw new UriFormatException (string.Format ("Uri is longer than the maximum {0} characters.", MaxUriLength));
2143 bool escape = false;
2144 foreach (char c in stringToEscape){
2145 if (NeedToEscapeUriChar (c)){
2151 return stringToEscape;
2153 StringBuilder sb = new StringBuilder ();
2154 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
2155 foreach (byte b in bytes){
2156 if (NeedToEscapeUriChar ((char) b))
2157 sb.Append (HexEscape ((char) b));
2159 sb.Append ((char) b);
2161 return sb.ToString ();
2164 public static bool IsWellFormedUriString (string uriString, UriKind uriKind)
2166 if (uriString == null)
2170 if (Uri.TryCreate (uriString, uriKind, out uri))
2171 return uri.IsWellFormedOriginalString ();
2175 public static bool TryCreate (string uriString, UriKind uriKind, out Uri result)
2179 Uri r = new Uri (uriString, uriKind, out success);
2188 // [MonoTODO ("rework code to avoid exception catching")]
2189 public static bool TryCreate (Uri baseUri, string relativeUri, out Uri result)
2192 if (relativeUri == null)
2196 Uri relative = new Uri (relativeUri, UriKind.RelativeOrAbsolute);
2197 if ((baseUri != null) && baseUri.IsAbsoluteUri) {
2198 // FIXME: this should call UriParser.Resolve
2199 result = new Uri (baseUri, relative);
2200 } else if (relative.IsAbsoluteUri) {
2201 // special case - see unit tests
2204 return (result != null);
2205 } catch (UriFormatException) {
2210 //[MonoTODO ("rework code to avoid exception catching")]
2211 public static bool TryCreate (Uri baseUri, Uri relativeUri, out Uri result)
2214 if ((baseUri == null) || !baseUri.IsAbsoluteUri)
2217 if (relativeUri == null)
2221 // FIXME: this should call UriParser.Resolve
2222 result = new Uri (baseUri, relativeUri.OriginalString);
2224 } catch (UriFormatException) {
2229 public static string UnescapeDataString (string stringToUnescape)
2231 return UnescapeDataString (stringToUnescape, false);
2234 internal static string UnescapeDataString (string stringToUnescape, bool safe)
2236 if (stringToUnescape == null)
2237 throw new ArgumentNullException ("stringToUnescape");
2239 if (stringToUnescape.IndexOf ('%') == -1 && stringToUnescape.IndexOf ('+') == -1)
2240 return stringToUnescape;
2242 StringBuilder output = new StringBuilder ();
2243 long len = stringToUnescape.Length;
2244 MemoryStream bytes = new MemoryStream ();
2247 for (int i = 0; i < len; i++) {
2248 if (stringToUnescape [i] == '%' && i + 2 < len && stringToUnescape [i + 1] != '%') {
2249 if (stringToUnescape [i + 1] == 'u' && i + 5 < len) {
2250 if (bytes.Length > 0) {
2251 output.Append (GetChars (bytes, Encoding.UTF8));
2252 bytes.SetLength (0);
2255 xchar = GetChar (stringToUnescape, i + 2, 4, safe);
2257 output.Append ((char) xchar);
2261 output.Append ('%');
2264 else if ((xchar = GetChar (stringToUnescape, i + 1, 2, safe)) != -1) {
2265 bytes.WriteByte ((byte) xchar);
2269 output.Append ('%');
2274 if (bytes.Length > 0) {
2275 output.Append (GetChars (bytes, Encoding.UTF8));
2276 bytes.SetLength (0);
2279 output.Append (stringToUnescape [i]);
2282 if (bytes.Length > 0) {
2283 output.Append (GetChars (bytes, Encoding.UTF8));
2287 return output.ToString ();
2290 private static int GetInt (byte b)
2293 if (c >= '0' && c <= '9')
2296 if (c >= 'a' && c <= 'f')
2297 return c - 'a' + 10;
2299 if (c >= 'A' && c <= 'F')
2300 return c - 'A' + 10;
2305 private static int GetChar (string str, int offset, int length, bool safe)
2308 int end = length + offset;
2309 for (int i = offset; i < end; i++) {
2314 int current = GetInt ((byte) c);
2317 val = (val << 4) + current;
2323 switch ((char) val) {
2330 case '&': // not documented
2337 private static char [] GetChars (MemoryStream b, Encoding e)
2339 return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
2343 private void EnsureAbsoluteUri ()
2346 throw new InvalidOperationException ("This operation is not supported for a relative URI.");