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 =
129 public Uri (string uriString) : this (uriString, UriKind.Absolute)
133 public Uri (string uriString) : this (uriString, false)
137 protected Uri (SerializationInfo serializationInfo, StreamingContext streamingContext)
139 string uri = serializationInfo.GetString ("AbsoluteUri");
140 if (uri.Length > 0) {
142 ParseUri(UriKind.Absolute);
144 uri = serializationInfo.GetString ("RelativeUri");
145 if (uri.Length > 0) {
147 ParseUri(UriKind.Relative);
149 throw new ArgumentException("Uri string was null or empty.");
154 public Uri (string uriString, UriKind uriKind)
160 case UriKind.Absolute:
162 throw new UriFormatException("Invalid URI: The format of the URI could not be "
165 case UriKind.Relative:
167 throw new UriFormatException("Invalid URI: The format of the URI could not be "
168 + "determined because the parameter 'uriString' represents an absolute URI.");
170 case UriKind.RelativeOrAbsolute:
173 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
174 throw new ArgumentException (msg);
179 // An exception-less constructor, returns success
180 // condition on the out parameter `success'.
182 Uri (string uriString, UriKind uriKind, out bool success)
184 if (uriString == null) {
189 if (uriKind != UriKind.RelativeOrAbsolute &&
190 uriKind != UriKind.Absolute &&
191 uriKind != UriKind.Relative) {
192 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
193 throw new ArgumentException (msg);
197 if (ParseNoExceptions (uriKind, uriString) != null)
203 case UriKind.Absolute:
207 case UriKind.Relative:
211 case UriKind.RelativeOrAbsolute:
220 public Uri (Uri baseUri, Uri relativeUri)
222 Merge (baseUri, relativeUri == null ? String.Empty : relativeUri.OriginalString);
223 // FIXME: this should call UriParser.Resolve
226 // note: doc says that dontEscape is always false but tests show otherwise
228 public Uri (string uriString, bool dontEscape)
230 userEscaped = dontEscape;
232 ParseUri (UriKind.Absolute);
234 throw new UriFormatException("Invalid URI: The format of the URI could not be "
235 + "determined: " + uriString);
238 public Uri (Uri baseUri, string relativeUri)
240 Merge (baseUri, relativeUri);
241 // FIXME: this should call UriParser.Resolve
244 [Obsolete ("dontEscape is always false")]
245 public Uri (Uri baseUri, string relativeUri, bool dontEscape)
247 userEscaped = dontEscape;
248 Merge (baseUri, relativeUri);
251 private void Merge (Uri baseUri, string relativeUri)
254 throw new ArgumentNullException ("baseUri");
255 if (!baseUri.IsAbsoluteUri)
256 throw new ArgumentOutOfRangeException ("baseUri");
257 if (relativeUri == null)
258 relativeUri = String.Empty;
260 // See RFC 2396 Par 5.2 and Appendix C
262 // Check Windows UNC (for // it is scheme/host separator)
263 if (relativeUri.Length >= 2 && relativeUri [0] == '\\' && relativeUri [1] == '\\') {
264 source = relativeUri;
265 ParseUri (UriKind.Absolute);
269 int pos = relativeUri.IndexOf (':');
272 int pos2 = relativeUri.IndexOfAny (new char [] {'/', '\\', '?'});
274 // pos2 < 0 ... e.g. mailto
275 // pos2 > pos ... to block ':' in query part
276 if (pos2 > pos || pos2 < 0) {
277 // in some cases, it is equivanent to new Uri (relativeUri, dontEscape):
278 // 1) when the URI scheme in the
279 // relative path is different from that
280 // of the baseUri, or
281 // 2) the URI scheme is non-standard
282 // ones (non-standard URIs are always
283 // treated as absolute here), or
284 // 3) the relative URI path is absolute.
285 if (String.CompareOrdinal (baseUri.Scheme, 0, relativeUri, 0, pos) != 0 ||
286 !IsPredefinedScheme (baseUri.Scheme) ||
287 (relativeUri.Length > pos + 1 && relativeUri [pos + 1] == '/')) {
289 if (Uri.TryCreate (relativeUri, UriKind.Absolute, out tmp)) {
290 source = relativeUri;
291 ParseUri (UriKind.Absolute);
293 } else if (pos == 1) {
294 // special case as this looks like a windows path
295 string msg = ParseAsWindowsAbsoluteFilePath (relativeUri);
297 throw new UriFormatException (msg);
299 // otherwise continue with 'full' relativeUri
302 relativeUri = relativeUri.Substring (pos + 1);
306 this.scheme = baseUri.scheme;
307 this.host = baseUri.host;
308 this.port = baseUri.port;
309 this.userinfo = baseUri.userinfo;
310 this.isUnc = baseUri.isUnc;
311 this.isUnixFilePath = baseUri.isUnixFilePath;
312 this.isOpaquePart = baseUri.isOpaquePart;
314 if (relativeUri.Length == 0) {
315 this.path = baseUri.path;
316 this.query = baseUri.query;
317 this.fragment = baseUri.fragment;
322 // Note that in relative constructor, file URI cannot handle '#' as a filename character, but just regarded as a fragment identifier.
323 string original_fragment = String.Empty;
324 pos = relativeUri.IndexOf ('#');
326 original_fragment = relativeUri.Substring (pos);
328 fragment = original_fragment;
330 fragment = "#" + EscapeString (relativeUri.Substring (pos+1));
331 relativeUri = pos == 0 ? String.Empty : relativeUri.Substring (0, pos);
334 bool consider_query = false;
337 pos = relativeUri.IndexOf ('?');
339 query = relativeUri.Substring (pos);
341 query = EscapeString (query);
342 #if !NET_4_0 && !MOONLIGHT && !MOBILE
343 consider_query = query.Length > 0;
345 relativeUri = pos == 0 ? String.Empty : relativeUri.Substring (0, pos);
346 } else if (relativeUri.Length == 0) {
347 // if there is no relative path then we keep the Query and Fragment from the absolute
348 query = baseUri.query;
351 if (relativeUri.Length > 0 && relativeUri [0] == '/') {
352 if (relativeUri.Length > 1 && relativeUri [1] == '/') {
353 source = scheme + ':' + relativeUri;
354 ParseUri (UriKind.Absolute);
359 path = EscapeString (path);
366 if ((relativeUri.Length > 0) || consider_query) {
367 pos = path.LastIndexOf ('/');
369 path = path.Substring (0, pos + 1);
372 if (relativeUri.Length == 0) {
373 // when merging URI the OriginalString is not quite original
374 source = GetLeftPart (UriPartial.Authority) + query + original_fragment;
384 pos = path.IndexOf ("./", startIndex);
388 path = path.Remove (0, 2);
389 else if (path [pos - 1] != '.')
390 path = path.Remove (pos, 2);
392 startIndex = pos + 1;
396 if (path.Length > 1 &&
397 path [path.Length - 1] == '.' &&
398 path [path.Length - 2] == '/')
399 path = path.Remove (path.Length - 1, 1);
404 pos = path.IndexOf ("/../", startIndex);
411 int pos2 = path.LastIndexOf ('/', pos - 1);
413 startIndex = pos + 1;
415 if (path.Substring (pos2 + 1, pos - pos2 - 1) != "..")
416 path = path.Remove (pos2 + 1, pos - pos2 + 3);
418 startIndex = pos + 1;
423 if (path.Length > 3 && path.EndsWith ("/..")) {
424 pos = path.LastIndexOf ('/', path.Length - 4);
426 if (path.Substring (pos + 1, path.Length - pos - 4) != "..")
427 path = path.Remove (pos + 1, path.Length - pos - 1);
431 while (path.StartsWith ("/../", StringComparison.Ordinal))
432 path = path.Substring (3);
435 path = EscapeString (path);
437 // when merging URI the OriginalString is not quite original
438 source = GetLeftPart (UriPartial.Authority) + path + query + original_fragment;
443 public string AbsolutePath {
445 EnsureAbsoluteUri ();
446 if (scheme == "mailto" || scheme == "file")
447 // faster (mailto) and special (file) cases
450 if (path.Length == 0) {
451 string start = scheme + SchemeDelimiter;
452 if (path.StartsWith (start, StringComparison.Ordinal))
461 public string AbsoluteUri {
463 EnsureAbsoluteUri ();
464 if (cachedAbsoluteUri == null) {
465 cachedAbsoluteUri = GetLeftPart (UriPartial.Path);
466 if (query.Length > 0)
467 cachedAbsoluteUri += query;
468 if (fragment.Length > 0)
469 cachedAbsoluteUri += fragment;
471 return cachedAbsoluteUri;
475 public string Authority {
477 EnsureAbsoluteUri ();
478 return (GetDefaultPort (Scheme) == port)
479 ? host : host + ":" + port;
483 public string Fragment {
485 EnsureAbsoluteUri ();
492 EnsureAbsoluteUri ();
497 public UriHostNameType HostNameType {
499 EnsureAbsoluteUri ();
500 UriHostNameType ret = CheckHostName (Host);
501 if (ret != UriHostNameType.Unknown)
504 if (scheme == "mailto")
505 return UriHostNameType.Basic;
506 return (IsFile) ? UriHostNameType.Basic : ret;
510 public bool IsDefaultPort {
512 EnsureAbsoluteUri ();
513 return GetDefaultPort (Scheme) == port;
519 EnsureAbsoluteUri ();
520 return (Scheme == UriSchemeFile);
524 public bool IsLoopback {
526 EnsureAbsoluteUri ();
528 if (Host.Length == 0) {
532 if (host == "loopback" || host == "localhost")
536 if (IPAddress.TryParse (host, out result))
537 if (IPAddress.Loopback.Equals (result))
541 if (IPv6Address.TryParse (host, out result6)){
542 if (IPv6Address.IsLoopback (result6))
551 // rule: This should be true only if
552 // - uri string starts from "\\", or
553 // - uri string starts from "//" (Samba way)
555 EnsureAbsoluteUri ();
560 private bool IsLocalIdenticalToAbsolutePath ()
565 if ((scheme == Uri.UriSchemeNews) || (scheme == Uri.UriSchemeNntp) || (scheme == Uri.UriSchemeFtp))
568 return IsWellFormedOriginalString ();
571 public string LocalPath {
573 EnsureAbsoluteUri ();
574 if (cachedLocalPath != null)
575 return cachedLocalPath;
577 if (IsLocalIdenticalToAbsolutePath ()) {
578 cachedLocalPath = Unescape (AbsolutePath);
579 return cachedLocalPath;
583 string p = Unescape (path);
584 bool windows = (path.Length > 3 && path [1] == ':' &&
585 (path [2] == '\\' || path [2] == '/'));
588 cachedLocalPath = p.Replace ('/', '\\');
592 // support *nix and W32 styles
593 if (path.Length > 1 && path [1] == ':')
594 cachedLocalPath = Unescape (path.Replace (Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));
596 // LAMESPEC: ok, now we cannot determine
597 // if such URI like "file://foo/bar" is
598 // Windows UNC or unix file path, so
599 // they should be handled differently.
600 else if (System.IO.Path.DirectorySeparatorChar == '\\') {
602 if (path.Length > 0) {
603 if ((path.Length > 1) || (path[0] != '/')) {
604 h += path.Replace ('/', '\\');
607 cachedLocalPath = "\\\\" + Unescape (h);
609 cachedLocalPath = Unescape (path);
611 if (cachedLocalPath.Length == 0)
612 cachedLocalPath = Path.DirectorySeparatorChar.ToString ();
613 return cachedLocalPath;
617 public string PathAndQuery {
619 EnsureAbsoluteUri ();
626 EnsureAbsoluteUri ();
631 public string Query {
633 EnsureAbsoluteUri ();
638 public string Scheme {
640 EnsureAbsoluteUri ();
645 public string [] Segments {
647 EnsureAbsoluteUri ();
649 // return a (pre-allocated) empty array
650 if (path.Length == 0)
652 // do not return the original array (since items can be changed)
653 if (segments != null)
654 return segments.ToArray ();
656 List<string> list = new List<string> ();
657 StringBuilder current = new StringBuilder ();
658 for (int i = 0; i < path.Length; i++) {
662 current.Append (path [i]);
663 list.Add (current.ToString ());
667 if ((i < path.Length - 2) && (path [i + 1] == '5' && path [i + 2] == 'C')) {
668 current.Append ("%5C");
669 list.Add (current.ToString ());
673 current.Append ('%');
677 current.Append (path [i]);
682 if (current.Length > 0)
683 list.Add (current.ToString ());
685 if (IsFile && (list.Count > 0)) {
686 string first = list [0];
687 if ((first.Length > 1) && (first [1] == ':')) {
688 list.Insert (0, "/");
692 return segments.ToArray ();
696 public bool UserEscaped {
697 get { return userEscaped; }
700 public string UserInfo {
702 EnsureAbsoluteUri ();
703 return userinfo == null ? String.Empty : userinfo;
707 public string DnsSafeHost {
709 EnsureAbsoluteUri ();
711 if (HostNameType == UriHostNameType.IPv6) {
712 host = Host.Substring (1, Host.Length - 2);
714 host += "%" + scope_id.ToString ();
716 return Unescape (host);
720 public bool IsAbsoluteUri {
721 get { return isAbsoluteUri; }
724 // LAMESPEC: source field is supplied in such case that this
725 // property makes sense. For such case that source field is
726 // not supplied (i.e. .ctor(Uri, string), this property
727 // makes no sense. To avoid silly regression it just returns
728 // ToString() value now. See bug #78374.
729 public string OriginalString {
730 get { return source != null ? source : ToString (); }
735 public static UriHostNameType CheckHostName (string name)
737 if (name == null || name.Length == 0)
738 return UriHostNameType.Unknown;
740 if (IsIPv4Address (name))
741 return UriHostNameType.IPv4;
743 if (IsDomainAddress (name))
744 return UriHostNameType.Dns;
747 if (IPv6Address.TryParse (name, out addr))
748 return UriHostNameType.IPv6;
750 return UriHostNameType.Unknown;
753 internal static bool IsIPv4Address (string name)
755 string [] captures = name.Split (new char [] {'.'});
756 if (captures.Length != 4)
759 for (int i = 0; i < 4; i++) {
762 length = captures [i].Length;
766 if (!UInt32.TryParse (captures [i], out number))
774 internal static bool IsDomainAddress (string name)
776 int len = name.Length;
779 for (int i = 0; i < len; i++) {
782 if (!Char.IsLetterOrDigit (c))
784 } else if (c == '.') {
785 // www..host.com is bad
786 if (i + 1 < len && name [i + 1] == '.')
790 } else if (!Char.IsLetterOrDigit (c) && c != '-' && c != '_') {
801 [Obsolete("This method does nothing, it has been obsoleted")]
802 protected virtual void Canonicalize ()
805 // This is flagged in the Microsoft documentation as used
806 // internally, no longer in use, and Obsolete.
810 [MonoTODO ("Find out what this should do")]
812 protected virtual void CheckSecurity ()
818 // defined in RFC3986 as = ALPHA *( ALPHA / DIGIT / "+" / "-" / ".")
819 public static bool CheckSchemeName (string schemeName)
821 if (schemeName == null || schemeName.Length == 0)
824 if (!IsAlpha (schemeName [0]))
827 int len = schemeName.Length;
828 for (int i = 1; i < len; i++) {
829 char c = schemeName [i];
830 if (!Char.IsDigit (c) && !IsAlpha (c) && c != '.' && c != '+' && c != '-')
837 private static bool IsAlpha (char c)
839 // as defined in rfc2234
840 // %x41-5A / %x61-7A (A-Z / a-z)
842 return (((i >= 0x41) && (i <= 0x5A)) || ((i >= 0x61) && (i <= 0x7A)));
845 public override bool Equals (object comparand)
847 if (comparand == null)
850 Uri uri = comparand as Uri;
851 if ((object) uri == null) {
852 string s = comparand as String;
856 if (!TryCreate (s, UriKind.RelativeOrAbsolute, out uri))
860 return InternalEquals (uri);
863 // Assumes: uri != null
864 bool InternalEquals (Uri uri)
866 if (this.isAbsoluteUri != uri.isAbsoluteUri)
868 if (!this.isAbsoluteUri)
869 return this.source == uri.source;
871 CultureInfo inv = CultureInfo.InvariantCulture;
872 return this.scheme.ToLower (inv) == uri.scheme.ToLower (inv)
873 && this.host.ToLower (inv) == uri.host.ToLower (inv)
874 && this.port == uri.port
875 && this.query == uri.query
876 && this.path == uri.path;
879 public static bool operator == (Uri uri1, Uri uri2)
881 return object.Equals (uri1, uri2);
884 public static bool operator != (Uri uri1, Uri uri2)
886 return !(uri1 == uri2);
889 public override int GetHashCode ()
891 if (cachedHashCode == 0) {
892 CultureInfo inv = CultureInfo.InvariantCulture;
894 cachedHashCode = scheme.ToLower (inv).GetHashCode ()
895 ^ host.ToLower (inv).GetHashCode ()
897 ^ query.GetHashCode ()
898 ^ path.GetHashCode ();
901 cachedHashCode = source.GetHashCode ();
904 return cachedHashCode;
907 public string GetLeftPart (UriPartial part)
909 EnsureAbsoluteUri ();
912 case UriPartial.Scheme :
913 return scheme + GetOpaqueWiseSchemeDelimiter ();
914 case UriPartial.Authority :
915 if ((scheme == Uri.UriSchemeMailto) || (scheme == Uri.UriSchemeNews))
918 StringBuilder s = new StringBuilder ();
920 s.Append (GetOpaqueWiseSchemeDelimiter ());
921 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
922 s.Append ('/'); // win32 file
923 if (userinfo != null)
924 s.Append (userinfo).Append ('@');
926 defaultPort = GetDefaultPort (scheme);
927 if ((port != -1) && (port != defaultPort))
928 s.Append (':').Append (port);
929 return s.ToString ();
930 case UriPartial.Path :
931 StringBuilder sb = new StringBuilder ();
933 sb.Append (GetOpaqueWiseSchemeDelimiter ());
934 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme))
935 sb.Append ('/'); // win32 file
936 if (userinfo != null)
937 sb.Append (userinfo).Append ('@');
939 defaultPort = GetDefaultPort (scheme);
940 if ((port != -1) && (port != defaultPort))
941 sb.Append (':').Append (port);
943 if (path.Length > 0) {
944 if (scheme == "mailto" || scheme == "news")
947 sb.Append (Reduce (path, CompactEscaped (scheme)));
949 return sb.ToString ();
954 public static int FromHex (char digit)
956 if ('0' <= digit && digit <= '9') {
957 return (int) (digit - '0');
960 if ('a' <= digit && digit <= 'f')
961 return (int) (digit - 'a' + 10);
963 if ('A' <= digit && digit <= 'F')
964 return (int) (digit - 'A' + 10);
966 throw new ArgumentException ("digit");
969 public static string HexEscape (char character)
971 if (character > 255) {
972 throw new ArgumentOutOfRangeException ("character");
975 return "%" + hexUpperChars [((character & 0xf0) >> 4)]
976 + hexUpperChars [((character & 0x0f))];
979 public static char HexUnescape (string pattern, ref int index)
982 throw new ArgumentException ("pattern");
984 if (index < 0 || index >= pattern.Length)
985 throw new ArgumentOutOfRangeException ("index");
987 if (!IsHexEncoding (pattern, index))
988 return pattern [index++];
991 int msb = FromHex (pattern [index++]);
992 int lsb = FromHex (pattern [index++]);
993 return (char) ((msb << 4) | lsb);
996 public static bool IsHexDigit (char character)
998 return (('0' <= character && character <= '9') ||
999 ('a' <= character && character <= 'f') ||
1000 ('A' <= character && character <= 'F'));
1003 public static bool IsHexEncoding (string pattern, int index)
1005 if ((index + 3) > pattern.Length)
1008 return ((pattern [index++] == '%') &&
1009 IsHexDigit (pattern [index++]) &&
1010 IsHexDigit (pattern [index]));
1014 // Implemented by copying most of the MakeRelative code
1016 public Uri MakeRelativeUri (Uri uri)
1018 #if NET_4_0 || MOONLIGHT || MOBILE
1020 throw new ArgumentNullException ("uri");
1022 if (Host != uri.Host || Scheme != uri.Scheme)
1025 string result = String.Empty;
1026 if (this.path != uri.path){
1027 string [] segments = this.Segments;
1028 string [] segments2 = uri.Segments;
1031 int max = Math.Min (segments.Length, segments2.Length);
1032 for (; k < max; k++)
1033 if (segments [k] != segments2 [k])
1036 for (int i = k; i < segments.Length && segments [i].EndsWith ("/"); i++)
1038 for (int i = k; i < segments2.Length; i++)
1039 result += segments2 [i];
1041 if (result == string.Empty)
1044 uri.AppendQueryAndFragment (ref result);
1046 return new Uri (result, UriKind.Relative);
1049 [Obsolete ("Use MakeRelativeUri(Uri uri) instead.")]
1050 public string MakeRelative (Uri toUri)
1052 if ((this.Scheme != toUri.Scheme) ||
1053 (this.Authority != toUri.Authority))
1054 return toUri.ToString ();
1056 string result = String.Empty;
1057 if (this.path != toUri.path){
1058 string [] segments = this.Segments;
1059 string [] segments2 = toUri.Segments;
1061 int max = Math.Min (segments.Length, segments2.Length);
1062 for (; k < max; k++)
1063 if (segments [k] != segments2 [k])
1066 for (int i = k + 1; i < segments.Length; i++)
1068 for (int i = k; i < segments2.Length; i++)
1069 result += segments2 [i];
1072 // Important: MakeRelative does not append fragment or query.
1077 void AppendQueryAndFragment (ref string result)
1079 if (query.Length > 0) {
1080 string q = query [0] == '?' ? '?' + Unescape (query.Substring (1), true, false) : Unescape (query, false);
1083 if (fragment.Length > 0)
1084 result += Unescape (fragment, true, false);
1087 public override string ToString ()
1089 if (cachedToString != null)
1090 return cachedToString;
1092 if (isAbsoluteUri) {
1093 cachedToString = Unescape (GetLeftPart (UriPartial.Path), true);
1094 AppendQueryAndFragment (ref cachedToString);
1096 // Everything is contained in path in this case.
1097 cachedToString = path;
1100 return cachedToString;
1103 protected void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
1105 if (this.isAbsoluteUri) {
1106 serializationInfo.AddValue ("AbsoluteUri", this.AbsoluteUri);
1108 serializationInfo.AddValue("AbsoluteUri", String.Empty);
1109 serializationInfo.AddValue("RelativeUri", this.OriginalString);
1113 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
1115 GetObjectData (info, context);
1122 protected virtual void Escape ()
1124 path = EscapeString (path);
1128 static string EscapeString (string str)
1131 protected static string EscapeString (string str)
1134 return EscapeString (str, Uri.EscapeCommonHexBrackets);
1137 private const string EscapeCommon = "<>%\"{}|\\^`";
1138 private const string EscapeReserved = ";/?:@&=+$,";
1139 private const string EscapeFragment = "#";
1140 private const string EscapeBrackets = "[]";
1142 private const string EscapeNews = EscapeCommon + EscapeBrackets + "?";
1143 private const string EscapeCommonHex = EscapeCommon + EscapeFragment;
1144 private const string EscapeCommonBrackets = EscapeCommon + EscapeBrackets;
1145 internal const string EscapeCommonHexBrackets = EscapeCommon + EscapeFragment + EscapeBrackets;
1146 internal const string EscapeCommonHexBracketsQuery = EscapeCommonHexBrackets + "?";
1148 internal static string EscapeString (string str, string escape)
1150 return EscapeString (str, escape, true);
1153 internal static string EscapeString (string str, string escape, bool nonAsciiEscape)
1155 if (String.IsNullOrEmpty (str))
1156 return String.Empty;
1158 StringBuilder s = new StringBuilder ();
1159 int len = str.Length;
1160 for (int i = 0; i < len; i++) {
1161 // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
1162 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
1163 // control = <US-ASCII coded characters 00-1F and 7F hexadecimal>
1164 // space = <US-ASCII coded character 20 hexadecimal>
1165 // delims = "<" | ">" | "#" | "%" | <">
1166 // unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
1168 // check for escape code already placed in str,
1169 // i.e. for encoding that follows the pattern
1170 // "%hexhex" in a string, where "hex" is a digit from 0-9
1171 // or a letter from A-F (case-insensitive).
1172 if (IsHexEncoding (str,i)) {
1173 // if ,yes , copy it as is
1174 s.Append(str.Substring (i, 3));
1180 bool outside_limited_ascii = ((c <= 0x20) || (c >= 0x7f));
1181 bool needs_escape = (escape.IndexOf (c) != -1);
1182 if (nonAsciiEscape && outside_limited_ascii) {
1183 byte [] data = Encoding.UTF8.GetBytes (new char [] { c });
1184 int length = data.Length;
1185 for (int j = 0; j < length; j++) {
1186 c = (char) data [j];
1187 if (needs_escape || nonAsciiEscape)
1188 s.Append (HexEscape (c));
1192 } else if (needs_escape) {
1193 s.Append (HexEscape (c));
1199 return s.ToString ();
1202 // On .NET 1.x, this method is called from .ctor(). When overriden, we
1203 // can avoid the "absolute uri" constraints of the .ctor() by
1204 // overriding with custom code.
1205 [Obsolete("The method has been deprecated. It is not used by the system.")]
1206 protected virtual void Parse ()
1210 private void ParseUri (UriKind kind)
1212 Parse (kind, source);
1217 // non-ascii characters are not escaped for the host name
1218 host = EscapeString (host, EscapeCommonHex, false);
1219 if (host.Length > 1 && host [0] != '[' && host [host.Length - 1] != ']') {
1220 // host name present (but not an IPv6 address)
1221 host = host.ToLower (CultureInfo.InvariantCulture);
1224 if (isAbsoluteUri && (path.Length > 0))
1225 path = EscapeString (path);
1229 string Unescape (string path)
1232 protected virtual string Unescape (string path)
1235 return Unescape (path, false, false);
1238 internal static string Unescape (string str, bool excludeSpecial)
1240 return Unescape (str, excludeSpecial, excludeSpecial);
1243 internal static string Unescape (string str, bool excludeSpecial, bool excludeBackslash)
1245 if (String.IsNullOrEmpty (str))
1246 return String.Empty;
1248 StringBuilder s = new StringBuilder ();
1249 int len = str.Length;
1250 for (int i = 0; i < len; i++) {
1254 char x = HexUnescapeMultiByte (str, ref i, out surrogate);
1255 if (excludeSpecial && x == '#')
1257 else if (excludeSpecial && x == '%')
1259 else if (excludeSpecial && x == '?')
1261 else if (excludeBackslash && x == '\\')
1265 if (surrogate != char.MinValue)
1266 s.Append (surrogate);
1272 return s.ToString ();
1278 private void ParseAsWindowsUNC (string uriString)
1280 scheme = UriSchemeFile;
1282 fragment = String.Empty;
1283 query = String.Empty;
1286 uriString = uriString.TrimStart (new char [] {'\\'});
1287 int pos = uriString.IndexOf ('\\');
1289 path = uriString.Substring (pos);
1290 host = uriString.Substring (0, pos);
1291 } else { // "\\\\server"
1293 path = String.Empty;
1295 path = path.Replace ("\\", "/");
1299 // Returns null on success, string with error on failure
1301 private string ParseAsWindowsAbsoluteFilePath (string uriString)
1303 if (uriString.Length > 2 && uriString [2] != '\\' && uriString [2] != '/')
1304 return "Relative file path is not allowed.";
1305 scheme = UriSchemeFile;
1306 host = String.Empty;
1308 path = uriString.Replace ("\\", "/");
1309 fragment = String.Empty;
1310 query = String.Empty;
1315 private void ParseAsUnixAbsoluteFilePath (string uriString)
1317 isUnixFilePath = true;
1318 scheme = UriSchemeFile;
1320 fragment = String.Empty;
1321 query = String.Empty;
1322 host = String.Empty;
1325 if (uriString.Length >= 2 && uriString [0] == '/' && uriString [1] == '/') {
1326 uriString = uriString.TrimStart (new char [] {'/'});
1327 // Now we don't regard //foo/bar as "foo" host.
1329 int pos = uriString.IndexOf ('/');
1331 path = '/' + uriString.Substring (pos + 1);
1332 host = uriString.Substring (0, pos);
1333 } else { // "///server"
1335 path = String.Empty;
1338 path = '/' + uriString;
1345 // This parse method will throw exceptions on failure
1347 private void Parse (UriKind kind, string uriString)
1349 if (uriString == null)
1350 throw new ArgumentNullException ("uriString");
1352 string s = ParseNoExceptions (kind, uriString);
1354 throw new UriFormatException (s);
1357 private bool SupportsQuery ()
1359 return ((scheme != Uri.UriSchemeNntp) && (scheme != Uri.UriSchemeFtp) && (scheme != Uri.UriSchemeFile));
1363 // This parse method will not throw exceptions on failure
1365 // Returns null on success, or a description of the error in the parsing
1367 private string ParseNoExceptions (UriKind kind, string uriString)
1372 // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1376 uriString = uriString.Trim();
1377 int len = uriString.Length;
1380 if (kind == UriKind.Relative || kind == UriKind.RelativeOrAbsolute){
1381 isAbsoluteUri = false;
1386 if (len <= 1 && (kind == UriKind.Absolute))
1387 return "Absolute URI is too short";
1392 // Identify Windows path, unix path, or standard URI.
1393 if (uriString [0] == '/' && Path.DirectorySeparatorChar == '/'){
1395 ParseAsUnixAbsoluteFilePath (uriString);
1397 isAbsoluteUri = false;
1399 if (kind == UriKind.Relative)
1400 isAbsoluteUri = false;
1403 } else if (uriString.Length >= 2 && uriString [0] == '\\' && uriString [1] == '\\') {
1405 ParseAsWindowsUNC (uriString);
1410 pos = uriString.IndexOf (':');
1412 if (kind == UriKind.Absolute)
1413 return "Invalid URI: The format of the URI could not be determined.";
1414 isAbsoluteUri = false;
1417 } else if (pos < 0) {
1419 isAbsoluteUri = false;
1422 } else if (pos == 1) {
1423 if (!IsAlpha (uriString [0])) {
1424 if (kind == UriKind.Absolute)
1425 return "Invalid URI: The URI scheme is not valid.";
1426 isAbsoluteUri = false;
1430 // This means 'a:' == windows full path.
1431 string msg = ParseAsWindowsAbsoluteFilePath (uriString);
1438 scheme = uriString.Substring (0, pos).ToLower (CultureInfo.InvariantCulture);
1440 // Check scheme name characters as specified in RFC2396.
1441 // Note: different checks in 1.x and 2.0
1442 if (!CheckSchemeName (scheme)) {
1443 if (kind == UriKind.Absolute)
1444 return "Invalid URI: The URI scheme is not valid.";
1445 isAbsoluteUri = false;
1450 scheme = TryGetKnownUriSchemeInstance (scheme);
1452 // from here we're practically working on uriString.Substring(startpos,endpos-startpos)
1453 int startpos = pos + 1;
1454 int endpos = uriString.Length;
1457 pos = uriString.IndexOf ('#', startpos);
1458 if (!IsUnc && pos != -1) {
1460 fragment = uriString.Substring (pos);
1462 fragment = "#" + EscapeString (uriString.Substring (pos+1));
1467 // special case: there is no query part for 'news'
1468 if (scheme == Uri.UriSchemeNews) {
1469 pos = scheme.Length + 1;
1470 path = EscapeString (uriString.Substring (pos, endpos - pos), EscapeNews);
1474 // special case: there is no query part for 'nntp', 'file' and 'ftp' but there is an host, port, user...
1475 if (SupportsQuery ()) {
1477 pos = uriString.IndexOf ('?', startpos, endpos-startpos);
1479 query = uriString.Substring (pos, endpos-pos);
1482 query = EscapeString (query);
1487 if (IsPredefinedScheme (scheme) && scheme != UriSchemeMailto && (
1488 (endpos-startpos < 2) ||
1489 (endpos-startpos >= 2 && uriString [startpos] == '/' && uriString [startpos+1] != '/')))
1490 return "Invalid URI: The Authority/Host could not be parsed.";
1493 bool startsWithSlashSlash = endpos-startpos >= 2 && uriString [startpos] == '/' && uriString [startpos+1] == '/';
1494 bool unixAbsPath = scheme == UriSchemeFile && startsWithSlashSlash && (endpos-startpos == 2 || uriString [startpos+2] == '/');
1495 bool windowsFilePath = false;
1496 if (startsWithSlashSlash) {
1497 if (kind == UriKind.Relative)
1498 return "Absolute URI when we expected a relative one";
1500 if (scheme != UriSchemeMailto)
1503 if (scheme == UriSchemeFile) {
1504 int num_leading_slash = 2;
1505 for (int i = startpos; i < endpos; i++) {
1506 if (uriString [i] != '/')
1508 num_leading_slash++;
1510 if (num_leading_slash >= 4) {
1511 unixAbsPath = false;
1512 while (startpos < endpos && uriString[startpos] == '/') {
1515 } else if (num_leading_slash >= 3) {
1520 if (endpos - startpos > 1 && uriString [startpos + 1] == ':') {
1521 unixAbsPath = false;
1522 windowsFilePath = true;
1525 } else if (!IsPredefinedScheme (scheme)) {
1526 path = uriString.Substring(startpos, endpos-startpos);
1527 isOpaquePart = true;
1535 pos = uriString.IndexOf ('/', startpos, endpos - startpos);
1536 if (pos == -1 && windowsFilePath)
1537 pos = uriString.IndexOf ('\\', startpos, endpos - startpos);
1540 path = uriString.Substring (pos, endpos - pos);
1541 if (!SupportsQuery ()) {
1542 if (scheme != Uri.UriSchemeNntp)
1543 path = path.Replace ('\\', '/');
1544 path = EscapeString (path, EscapeNews);
1548 if (scheme != Uri.UriSchemeMailto)
1556 pos = uriString.IndexOf ('@', startpos, endpos-startpos);
1558 // supplying username / password on a file URI is not supported
1559 if (scheme == UriSchemeFile)
1560 return "Invalid host";
1561 userinfo = uriString.Substring (startpos, pos-startpos);
1566 bool valid_port = true;
1571 pos = uriString.LastIndexOf (':', endpos-1, endpos-startpos);
1572 if (pos != -1 && pos != endpos - 1) {
1573 string portStr = uriString.Substring(pos + 1, endpos - (pos + 1));
1574 if (portStr.Length > 0 && portStr[portStr.Length - 1] != ']') {
1575 if (!Int32.TryParse (portStr, NumberStyles.None, CultureInfo.InvariantCulture, out port) ||
1576 port < 0 || port > UInt16.MaxValue)
1577 valid_port = false; // delay reporting
1582 port = GetDefaultPort (scheme);
1585 } else if (!IsFile) {
1586 // if no port is specified by a colon ':' is present then we must ignore it
1587 // since it would be part of the host name and, as such, would be invalid
1588 if (pos == endpos - 1)
1592 port = GetDefaultPort (scheme);
1596 uriString = uriString.Substring(startpos, endpos-startpos);
1600 path = Reduce ('/' + uriString, true);
1601 host = String.Empty;
1602 } else if (host.Length == 2 && host [1] == ':') {
1603 if (scheme != UriSchemeFile) {
1604 host = host [0].ToString ();
1608 host = String.Empty;
1610 } else if (isUnixFilePath) {
1611 uriString = "//" + uriString;
1612 host = String.Empty;
1613 } else if (scheme == UriSchemeFile) {
1614 // under Windows all file:// URI are considered UNC, which is not the case other MacOS (e.g. Silverlight)
1616 } else if (host.Length == 0 &&
1617 (scheme == UriSchemeHttp || scheme == UriSchemeGopher || scheme == UriSchemeNntp ||
1618 scheme == UriSchemeHttps || scheme == UriSchemeFtp)) {
1619 return "Invalid URI: The Authority/Host could not be parsed.";
1622 if (host.Length > 0) {
1623 switch (CheckHostName (host)) {
1624 case UriHostNameType.Unknown:
1625 if ((host [0] == ':') || (host [0] == '@'))
1626 return "Invalid URI: The hostname could not be parsed.";
1627 if (host.IndexOf (':') != -1)
1628 return "Invalid URI: Invalid port specified.";
1629 if (Parser is DefaultUriParser || Parser == null)
1630 return "Invalid URI: The hostname could not be parsed.";
1632 case UriHostNameType.IPv6:
1633 IPv6Address ipv6addr;
1634 if (IPv6Address.TryParse (host, out ipv6addr)) {
1635 host = "[" + ipv6addr.ToString (true) + "]";
1636 scope_id = ipv6addr.ScopeId;
1641 // delayed reporting (to throw the expected exception in the right order)
1643 return "Invalid URI: Invalid port number";
1645 UriFormatException ex = null;
1647 Parser.InitializeAndValidate (this, out ex);
1651 if ((scheme != Uri.UriSchemeMailto) && (scheme != Uri.UriSchemeFile)) {
1652 path = Reduce (path, CompactEscaped (scheme));
1658 private static string TryGetKnownUriSchemeInstance (string scheme)
1660 foreach (string knownScheme in knownUriSchemes) {
1661 if (knownScheme == scheme)
1668 private static bool CompactEscaped (string scheme)
1670 if (scheme == null || scheme.Length < 4)
1673 char first = scheme [0];
1675 return scheme == "http" || scheme == "https";
1676 } else if (first == 'f' && scheme == "file"){
1678 } else if (first == 'n')
1679 return scheme == "net.pipe" || scheme == "net.tcp";
1684 // replace '\', %5C ('\') and %2f ('/') into '/'
1685 // replace %2e ('.') into '.'
1686 private static string NormalizePath (string path)
1688 StringBuilder res = new StringBuilder ();
1689 for (int i = 0; i < path.Length; i++) {
1696 if (i < path.Length - 2) {
1697 char c1 = path [i + 1];
1698 char c2 = Char.ToUpper (path [i + 2]);
1699 if ((c1 == '2') && (c2 == 'E')) {
1702 } else if (((c1 == '2') && (c2 == 'F')) || ((c1 == '5') && (c2 == 'C'))) {
1711 return res.ToString ();
1714 // This is called "compacting" in the MSDN documentation
1715 private static string Reduce (string path, bool compact_escaped)
1717 // quick out, allocation-free, for a common case
1721 if (compact_escaped && (path.IndexOf ('%') != -1)) {
1722 // replace '\', %2f, %5c with '/' and replace %2e with '.'
1723 // other escaped values seems to survive this step
1724 path = NormalizePath (path);
1726 // (always) replace '\' with '/'
1727 path = path.Replace ('\\', '/');
1730 List<string> result = new List<string> ();
1733 for (int startpos = 0; startpos < path.Length; ) {
1734 int endpos = path.IndexOf ('/', startpos);
1736 endpos = path.Length;
1737 string current = path.Substring (startpos, endpos-startpos);
1738 startpos = endpos + 1;
1739 if ((begin && current.Length == 0) || current == "." ) {
1745 if (current == "..") {
1746 int resultCount = result.Count;
1747 // in 2.0 profile, skip leading ".." parts
1748 if (resultCount == 0) {
1752 result.RemoveAt (resultCount - 1);
1756 result.Add (current);
1759 if (result.Count == 0)
1762 StringBuilder res = new StringBuilder ();
1764 if (path [0] == '/')
1768 foreach (string part in result) {
1777 if (path [path.Length - 1] == '/')
1780 return res.ToString();
1783 // A variant of HexUnescape() which can decode multi-byte escaped
1784 // sequences such as (e.g.) %E3%81%8B into a single character
1785 private static char HexUnescapeMultiByte (string pattern, ref int index, out char surrogate)
1787 surrogate = char.MinValue;
1789 if (pattern == null)
1790 throw new ArgumentException ("pattern");
1792 if (index < 0 || index >= pattern.Length)
1793 throw new ArgumentOutOfRangeException ("index");
1795 if (!IsHexEncoding (pattern, index))
1796 return pattern [index++];
1798 int orig_index = index++;
1799 int msb = FromHex (pattern [index++]);
1800 int lsb = FromHex (pattern [index++]);
1802 // We might be dealing with a multi-byte character:
1803 // The number of ones at the top-end of the first byte will tell us
1804 // how many bytes will make up this character.
1807 while ((msb_copy & 0x8) == 0x8) {
1812 // We might be dealing with a single-byte character:
1813 // If there was only 0 or 1 leading ones then we're not dealing
1814 // with a multi-byte character.
1816 return (char) ((msb << 4) | lsb);
1818 // Now that we know how many bytes *should* follow, we'll check them
1819 // to ensure we are dealing with a valid multi-byte character.
1820 byte [] chars = new byte [num_bytes];
1821 bool all_invalid = false;
1822 chars[0] = (byte) ((msb << 4) | lsb);
1824 for (int i = 1; i < num_bytes; i++) {
1825 if (!IsHexEncoding (pattern, index++)) {
1830 // All following bytes must be in the form 10xxxxxx
1831 int cur_msb = FromHex (pattern [index++]);
1832 if ((cur_msb & 0xc) != 0x8) {
1837 int cur_lsb = FromHex (pattern [index++]);
1838 chars[i] = (byte) ((cur_msb << 4) | cur_lsb);
1841 // If what looked like a multi-byte character is invalid, then we'll
1842 // just return the first byte as a single byte character.
1844 index = orig_index + 3;
1845 return (char) chars[0];
1848 // Otherwise, we're dealing with a valid multi-byte character.
1849 // We need to ignore the leading ones from the first byte:
1850 byte mask = (byte) 0xFF;
1851 mask >>= (num_bytes + 1);
1852 int result = chars[0] & mask;
1854 // The result will now be built up from the following bytes.
1855 for (int i = 1; i < num_bytes; i++) {
1856 // Ignore upper two bits
1858 result |= (chars[i] & 0x3F);
1861 if (result <= 0xFFFF) {
1862 return (char) result;
1864 // We need to handle this as a UTF16 surrogate (i.e. return
1867 surrogate = (char) ((result & 0x3FF) | 0xDC00);
1868 return (char) ((result >> 10) | 0xD800);
1872 private struct UriScheme
1874 public string scheme;
1875 public string delimiter;
1876 public int defaultPort;
1878 public UriScheme (string s, string d, int p)
1886 static UriScheme [] schemes = new UriScheme [] {
1887 new UriScheme (UriSchemeHttp, SchemeDelimiter, 80),
1888 new UriScheme (UriSchemeHttps, SchemeDelimiter, 443),
1889 new UriScheme (UriSchemeFtp, SchemeDelimiter, 21),
1890 new UriScheme (UriSchemeFile, SchemeDelimiter, -1),
1891 new UriScheme (UriSchemeMailto, ":", 25),
1892 new UriScheme (UriSchemeNews, ":", 119),
1893 new UriScheme (UriSchemeNntp, SchemeDelimiter, 119),
1894 new UriScheme (UriSchemeGopher, SchemeDelimiter, 70),
1897 internal static string GetSchemeDelimiter (string scheme)
1899 for (int i = 0; i < schemes.Length; i++)
1900 if (schemes [i].scheme == scheme)
1901 return schemes [i].delimiter;
1902 return Uri.SchemeDelimiter;
1905 internal static int GetDefaultPort (string scheme)
1907 UriParser parser = UriParser.GetParser (scheme);
1910 return parser.DefaultPort;
1913 private string GetOpaqueWiseSchemeDelimiter ()
1918 return GetSchemeDelimiter (scheme);
1922 protected virtual bool IsBadFileSystemCharacter (char character)
1924 // It does not always overlap with InvalidPathChars.
1925 int chInt = (int) character;
1926 if (chInt < 32 || (chInt < 64 && chInt > 57))
1945 protected static bool IsExcludedCharacter (char character)
1947 if (character <= 32 || character >= 127)
1950 if (character == '"' || character == '#' || character == '%' || character == '<' ||
1951 character == '>' || character == '[' || character == '\\' || character == ']' ||
1952 character == '^' || character == '`' || character == '{' || character == '|' ||
1958 internal static bool MaybeUri (string s)
1960 int p = s.IndexOf (':');
1967 return IsPredefinedScheme (s.Substring (0, p));
1971 // Using a simple block of if's is twice as slow as the compiler generated
1972 // switch statement. But using this tuned code is faster than the
1973 // compiler generated code, with a million loops on x86-64:
1975 // With "http": .10 vs .51 (first check)
1976 // with "https": .16 vs .51 (second check)
1977 // with "foo": .22 vs .31 (never found)
1978 // with "mailto": .12 vs .51 (last check)
1981 private static bool IsPredefinedScheme (string scheme)
1983 if (scheme == null || scheme.Length < 3)
1986 char c = scheme [0];
1988 return (scheme == "http" || scheme == "https");
1990 return (scheme == "file" || scheme == "ftp");
1995 return (scheme == "news" || scheme == "net.pipe" || scheme == "net.tcp");
1996 if (scheme == "nntp")
2000 if ((c == 'g' && scheme == "gopher") || (c == 'm' && scheme == "mailto"))
2007 protected virtual bool IsReservedCharacter (char character)
2009 if (character == '$' || character == '&' || character == '+' || character == ',' ||
2010 character == '/' || character == ':' || character == ';' || character == '=' ||
2017 private UriParser parser;
2019 private UriParser Parser {
2021 if (parser == null) {
2022 parser = UriParser.GetParser (Scheme);
2023 // no specific parser ? then use a default one
2025 parser = new DefaultUriParser ("*");
2029 set { parser = value; }
2032 public string GetComponents (UriComponents components, UriFormat format)
2034 return Parser.GetComponents (this, components, format);
2037 public bool IsBaseOf (Uri uri)
2039 #if NET_4_0 || MOONLIGHT || MOBILE
2041 throw new ArgumentNullException ("uri");
2043 return Parser.IsBaseOf (this, uri);
2046 public bool IsWellFormedOriginalString ()
2048 // funny, but it does not use the Parser's IsWellFormedOriginalString().
2049 // Also, it seems we need to *not* escape hex.
2050 return EscapeString (OriginalString, EscapeCommonBrackets) == OriginalString;
2055 private const int MaxUriLength = 32766;
2057 public static int Compare (Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType)
2059 if ((comparisonType < StringComparison.CurrentCulture) || (comparisonType > StringComparison.OrdinalIgnoreCase)) {
2060 string msg = Locale.GetText ("Invalid StringComparison value '{0}'", comparisonType);
2061 throw new ArgumentException ("comparisonType", msg);
2064 if ((uri1 == null) && (uri2 == null))
2067 string s1 = uri1.GetComponents (partsToCompare, compareFormat);
2068 string s2 = uri2.GetComponents (partsToCompare, compareFormat);
2069 return String.Compare (s1, s2, comparisonType);
2073 // The rules for EscapeDataString
2075 static bool NeedToEscapeDataChar (char b)
2078 // .NET 4.0 follows RFC 3986 Unreserved Characters
2079 return !((b >= 'A' && b <= 'Z') ||
2080 (b >= 'a' && b <= 'z') ||
2081 (b >= '0' && b <= '9') ||
2082 b == '-' || b == '.' || b == '_' || b == '~');
2084 return !((b >= 'A' && b <= 'Z') ||
2085 (b >= 'a' && b <= 'z') ||
2086 (b >= '0' && b <= '9') ||
2087 b == '_' || b == '~' || b == '!' || b == '\'' ||
2088 b == '(' || b == ')' || b == '*' || b == '-' || b == '.');
2092 public static string EscapeDataString (string stringToEscape)
2094 if (stringToEscape == null)
2095 throw new ArgumentNullException ("stringToEscape");
2097 if (stringToEscape.Length > MaxUriLength) {
2098 throw new UriFormatException (string.Format ("Uri is longer than the maximum {0} characters.", MaxUriLength));
2101 bool escape = false;
2102 foreach (char c in stringToEscape){
2103 if (NeedToEscapeDataChar (c)){
2109 return stringToEscape;
2112 StringBuilder sb = new StringBuilder ();
2113 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
2114 foreach (byte b in bytes){
2115 if (NeedToEscapeDataChar ((char) b))
2116 sb.Append (HexEscape ((char) b));
2118 sb.Append ((char) b);
2120 return sb.ToString ();
2124 // The rules for EscapeUriString
2126 static bool NeedToEscapeUriChar (char b)
2128 if ((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '&' && b <= ';'))
2141 // .NET 4.0 follows RFC 3986
2151 public static string EscapeUriString (string stringToEscape)
2153 if (stringToEscape == null)
2154 throw new ArgumentNullException ("stringToEscape");
2156 if (stringToEscape.Length > MaxUriLength) {
2157 throw new UriFormatException (string.Format ("Uri is longer than the maximum {0} characters.", MaxUriLength));
2160 bool escape = false;
2161 foreach (char c in stringToEscape){
2162 if (NeedToEscapeUriChar (c)){
2168 return stringToEscape;
2170 StringBuilder sb = new StringBuilder ();
2171 byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
2172 foreach (byte b in bytes){
2173 if (NeedToEscapeUriChar ((char) b))
2174 sb.Append (HexEscape ((char) b));
2176 sb.Append ((char) b);
2178 return sb.ToString ();
2181 public static bool IsWellFormedUriString (string uriString, UriKind uriKind)
2183 if (uriString == null)
2187 if (Uri.TryCreate (uriString, uriKind, out uri))
2188 return uri.IsWellFormedOriginalString ();
2192 public static bool TryCreate (string uriString, UriKind uriKind, out Uri result)
2196 Uri r = new Uri (uriString, uriKind, out success);
2205 // [MonoTODO ("rework code to avoid exception catching")]
2206 public static bool TryCreate (Uri baseUri, string relativeUri, out Uri result)
2209 if (relativeUri == null)
2213 Uri relative = new Uri (relativeUri, UriKind.RelativeOrAbsolute);
2214 if ((baseUri != null) && baseUri.IsAbsoluteUri) {
2215 // FIXME: this should call UriParser.Resolve
2216 result = new Uri (baseUri, relative);
2217 } else if (relative.IsAbsoluteUri) {
2218 // special case - see unit tests
2221 return (result != null);
2222 } catch (UriFormatException) {
2227 //[MonoTODO ("rework code to avoid exception catching")]
2228 public static bool TryCreate (Uri baseUri, Uri relativeUri, out Uri result)
2231 if ((baseUri == null) || !baseUri.IsAbsoluteUri)
2233 #if NET_4_0 || MOONLIGHT || MOBILE
2234 if (relativeUri == null)
2238 // FIXME: this should call UriParser.Resolve
2239 result = new Uri (baseUri, relativeUri.OriginalString);
2241 } catch (UriFormatException) {
2246 public static string UnescapeDataString (string stringToUnescape)
2248 return UnescapeDataString (stringToUnescape, false);
2251 internal static string UnescapeDataString (string stringToUnescape, bool safe)
2253 if (stringToUnescape == null)
2254 throw new ArgumentNullException ("stringToUnescape");
2256 if (stringToUnescape.IndexOf ('%') == -1 && stringToUnescape.IndexOf ('+') == -1)
2257 return stringToUnescape;
2259 StringBuilder output = new StringBuilder ();
2260 long len = stringToUnescape.Length;
2261 MemoryStream bytes = new MemoryStream ();
2264 for (int i = 0; i < len; i++) {
2265 if (stringToUnescape [i] == '%' && i + 2 < len && stringToUnescape [i + 1] != '%') {
2266 if (stringToUnescape [i + 1] == 'u' && i + 5 < len) {
2267 if (bytes.Length > 0) {
2268 output.Append (GetChars (bytes, Encoding.UTF8));
2269 bytes.SetLength (0);
2272 xchar = GetChar (stringToUnescape, i + 2, 4, safe);
2274 output.Append ((char) xchar);
2278 output.Append ('%');
2281 else if ((xchar = GetChar (stringToUnescape, i + 1, 2, safe)) != -1) {
2282 bytes.WriteByte ((byte) xchar);
2286 output.Append ('%');
2291 if (bytes.Length > 0) {
2292 output.Append (GetChars (bytes, Encoding.UTF8));
2293 bytes.SetLength (0);
2296 output.Append (stringToUnescape [i]);
2299 if (bytes.Length > 0) {
2300 output.Append (GetChars (bytes, Encoding.UTF8));
2304 return output.ToString ();
2307 private static int GetInt (byte b)
2310 if (c >= '0' && c <= '9')
2313 if (c >= 'a' && c <= 'f')
2314 return c - 'a' + 10;
2316 if (c >= 'A' && c <= 'F')
2317 return c - 'A' + 10;
2322 private static int GetChar (string str, int offset, int length, bool safe)
2325 int end = length + offset;
2326 for (int i = offset; i < end; i++) {
2331 int current = GetInt ((byte) c);
2334 val = (val << 4) + current;
2340 switch ((char) val) {
2347 case '&': // not documented
2354 private static char [] GetChars (MemoryStream b, Encoding e)
2356 return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
2360 private void EnsureAbsoluteUri ()
2363 throw new InvalidOperationException ("This operation is not supported for a relative URI.");