2 // Copied from System.Web.HttpUtility and marked internal
5 // Patrik Torstensson (Patrik.Torstensson@labs2.com)
6 // Wictor Wilén (decode/encode functions) (wictor@ibizkit.se)
7 // Tim Coleman (tim@timcoleman.com)
8 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
10 // Copyright (C) 2005-2009 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.Collections.Generic;
34 using System.Collections.Specialized;
35 using System.Globalization;
37 using System.Security.Permissions;
40 namespace System.Net {
42 internal sealed class HttpUtility
44 sealed class HttpQSCollection : NameValueCollection
46 public override string ToString ()
51 StringBuilder sb = new StringBuilder ();
52 string [] keys = AllKeys;
53 for (int i = 0; i < count; i++) {
54 sb.AppendFormat ("{0}={1}&", keys [i], this [keys [i]]);
58 return sb.ToString ();
63 static Hashtable entities;
64 static object lock_ = new object ();
68 static Hashtable Entities {
81 static void InitEntities ()
83 // Build the hash table of HTML entity references. This list comes
84 // from the HTML 4.01 W3C recommendation.
85 entities = new Hashtable ();
86 entities.Add ("nbsp", '\u00A0');
87 entities.Add ("iexcl", '\u00A1');
88 entities.Add ("cent", '\u00A2');
89 entities.Add ("pound", '\u00A3');
90 entities.Add ("curren", '\u00A4');
91 entities.Add ("yen", '\u00A5');
92 entities.Add ("brvbar", '\u00A6');
93 entities.Add ("sect", '\u00A7');
94 entities.Add ("uml", '\u00A8');
95 entities.Add ("copy", '\u00A9');
96 entities.Add ("ordf", '\u00AA');
97 entities.Add ("laquo", '\u00AB');
98 entities.Add ("not", '\u00AC');
99 entities.Add ("shy", '\u00AD');
100 entities.Add ("reg", '\u00AE');
101 entities.Add ("macr", '\u00AF');
102 entities.Add ("deg", '\u00B0');
103 entities.Add ("plusmn", '\u00B1');
104 entities.Add ("sup2", '\u00B2');
105 entities.Add ("sup3", '\u00B3');
106 entities.Add ("acute", '\u00B4');
107 entities.Add ("micro", '\u00B5');
108 entities.Add ("para", '\u00B6');
109 entities.Add ("middot", '\u00B7');
110 entities.Add ("cedil", '\u00B8');
111 entities.Add ("sup1", '\u00B9');
112 entities.Add ("ordm", '\u00BA');
113 entities.Add ("raquo", '\u00BB');
114 entities.Add ("frac14", '\u00BC');
115 entities.Add ("frac12", '\u00BD');
116 entities.Add ("frac34", '\u00BE');
117 entities.Add ("iquest", '\u00BF');
118 entities.Add ("Agrave", '\u00C0');
119 entities.Add ("Aacute", '\u00C1');
120 entities.Add ("Acirc", '\u00C2');
121 entities.Add ("Atilde", '\u00C3');
122 entities.Add ("Auml", '\u00C4');
123 entities.Add ("Aring", '\u00C5');
124 entities.Add ("AElig", '\u00C6');
125 entities.Add ("Ccedil", '\u00C7');
126 entities.Add ("Egrave", '\u00C8');
127 entities.Add ("Eacute", '\u00C9');
128 entities.Add ("Ecirc", '\u00CA');
129 entities.Add ("Euml", '\u00CB');
130 entities.Add ("Igrave", '\u00CC');
131 entities.Add ("Iacute", '\u00CD');
132 entities.Add ("Icirc", '\u00CE');
133 entities.Add ("Iuml", '\u00CF');
134 entities.Add ("ETH", '\u00D0');
135 entities.Add ("Ntilde", '\u00D1');
136 entities.Add ("Ograve", '\u00D2');
137 entities.Add ("Oacute", '\u00D3');
138 entities.Add ("Ocirc", '\u00D4');
139 entities.Add ("Otilde", '\u00D5');
140 entities.Add ("Ouml", '\u00D6');
141 entities.Add ("times", '\u00D7');
142 entities.Add ("Oslash", '\u00D8');
143 entities.Add ("Ugrave", '\u00D9');
144 entities.Add ("Uacute", '\u00DA');
145 entities.Add ("Ucirc", '\u00DB');
146 entities.Add ("Uuml", '\u00DC');
147 entities.Add ("Yacute", '\u00DD');
148 entities.Add ("THORN", '\u00DE');
149 entities.Add ("szlig", '\u00DF');
150 entities.Add ("agrave", '\u00E0');
151 entities.Add ("aacute", '\u00E1');
152 entities.Add ("acirc", '\u00E2');
153 entities.Add ("atilde", '\u00E3');
154 entities.Add ("auml", '\u00E4');
155 entities.Add ("aring", '\u00E5');
156 entities.Add ("aelig", '\u00E6');
157 entities.Add ("ccedil", '\u00E7');
158 entities.Add ("egrave", '\u00E8');
159 entities.Add ("eacute", '\u00E9');
160 entities.Add ("ecirc", '\u00EA');
161 entities.Add ("euml", '\u00EB');
162 entities.Add ("igrave", '\u00EC');
163 entities.Add ("iacute", '\u00ED');
164 entities.Add ("icirc", '\u00EE');
165 entities.Add ("iuml", '\u00EF');
166 entities.Add ("eth", '\u00F0');
167 entities.Add ("ntilde", '\u00F1');
168 entities.Add ("ograve", '\u00F2');
169 entities.Add ("oacute", '\u00F3');
170 entities.Add ("ocirc", '\u00F4');
171 entities.Add ("otilde", '\u00F5');
172 entities.Add ("ouml", '\u00F6');
173 entities.Add ("divide", '\u00F7');
174 entities.Add ("oslash", '\u00F8');
175 entities.Add ("ugrave", '\u00F9');
176 entities.Add ("uacute", '\u00FA');
177 entities.Add ("ucirc", '\u00FB');
178 entities.Add ("uuml", '\u00FC');
179 entities.Add ("yacute", '\u00FD');
180 entities.Add ("thorn", '\u00FE');
181 entities.Add ("yuml", '\u00FF');
182 entities.Add ("fnof", '\u0192');
183 entities.Add ("Alpha", '\u0391');
184 entities.Add ("Beta", '\u0392');
185 entities.Add ("Gamma", '\u0393');
186 entities.Add ("Delta", '\u0394');
187 entities.Add ("Epsilon", '\u0395');
188 entities.Add ("Zeta", '\u0396');
189 entities.Add ("Eta", '\u0397');
190 entities.Add ("Theta", '\u0398');
191 entities.Add ("Iota", '\u0399');
192 entities.Add ("Kappa", '\u039A');
193 entities.Add ("Lambda", '\u039B');
194 entities.Add ("Mu", '\u039C');
195 entities.Add ("Nu", '\u039D');
196 entities.Add ("Xi", '\u039E');
197 entities.Add ("Omicron", '\u039F');
198 entities.Add ("Pi", '\u03A0');
199 entities.Add ("Rho", '\u03A1');
200 entities.Add ("Sigma", '\u03A3');
201 entities.Add ("Tau", '\u03A4');
202 entities.Add ("Upsilon", '\u03A5');
203 entities.Add ("Phi", '\u03A6');
204 entities.Add ("Chi", '\u03A7');
205 entities.Add ("Psi", '\u03A8');
206 entities.Add ("Omega", '\u03A9');
207 entities.Add ("alpha", '\u03B1');
208 entities.Add ("beta", '\u03B2');
209 entities.Add ("gamma", '\u03B3');
210 entities.Add ("delta", '\u03B4');
211 entities.Add ("epsilon", '\u03B5');
212 entities.Add ("zeta", '\u03B6');
213 entities.Add ("eta", '\u03B7');
214 entities.Add ("theta", '\u03B8');
215 entities.Add ("iota", '\u03B9');
216 entities.Add ("kappa", '\u03BA');
217 entities.Add ("lambda", '\u03BB');
218 entities.Add ("mu", '\u03BC');
219 entities.Add ("nu", '\u03BD');
220 entities.Add ("xi", '\u03BE');
221 entities.Add ("omicron", '\u03BF');
222 entities.Add ("pi", '\u03C0');
223 entities.Add ("rho", '\u03C1');
224 entities.Add ("sigmaf", '\u03C2');
225 entities.Add ("sigma", '\u03C3');
226 entities.Add ("tau", '\u03C4');
227 entities.Add ("upsilon", '\u03C5');
228 entities.Add ("phi", '\u03C6');
229 entities.Add ("chi", '\u03C7');
230 entities.Add ("psi", '\u03C8');
231 entities.Add ("omega", '\u03C9');
232 entities.Add ("thetasym", '\u03D1');
233 entities.Add ("upsih", '\u03D2');
234 entities.Add ("piv", '\u03D6');
235 entities.Add ("bull", '\u2022');
236 entities.Add ("hellip", '\u2026');
237 entities.Add ("prime", '\u2032');
238 entities.Add ("Prime", '\u2033');
239 entities.Add ("oline", '\u203E');
240 entities.Add ("frasl", '\u2044');
241 entities.Add ("weierp", '\u2118');
242 entities.Add ("image", '\u2111');
243 entities.Add ("real", '\u211C');
244 entities.Add ("trade", '\u2122');
245 entities.Add ("alefsym", '\u2135');
246 entities.Add ("larr", '\u2190');
247 entities.Add ("uarr", '\u2191');
248 entities.Add ("rarr", '\u2192');
249 entities.Add ("darr", '\u2193');
250 entities.Add ("harr", '\u2194');
251 entities.Add ("crarr", '\u21B5');
252 entities.Add ("lArr", '\u21D0');
253 entities.Add ("uArr", '\u21D1');
254 entities.Add ("rArr", '\u21D2');
255 entities.Add ("dArr", '\u21D3');
256 entities.Add ("hArr", '\u21D4');
257 entities.Add ("forall", '\u2200');
258 entities.Add ("part", '\u2202');
259 entities.Add ("exist", '\u2203');
260 entities.Add ("empty", '\u2205');
261 entities.Add ("nabla", '\u2207');
262 entities.Add ("isin", '\u2208');
263 entities.Add ("notin", '\u2209');
264 entities.Add ("ni", '\u220B');
265 entities.Add ("prod", '\u220F');
266 entities.Add ("sum", '\u2211');
267 entities.Add ("minus", '\u2212');
268 entities.Add ("lowast", '\u2217');
269 entities.Add ("radic", '\u221A');
270 entities.Add ("prop", '\u221D');
271 entities.Add ("infin", '\u221E');
272 entities.Add ("ang", '\u2220');
273 entities.Add ("and", '\u2227');
274 entities.Add ("or", '\u2228');
275 entities.Add ("cap", '\u2229');
276 entities.Add ("cup", '\u222A');
277 entities.Add ("int", '\u222B');
278 entities.Add ("there4", '\u2234');
279 entities.Add ("sim", '\u223C');
280 entities.Add ("cong", '\u2245');
281 entities.Add ("asymp", '\u2248');
282 entities.Add ("ne", '\u2260');
283 entities.Add ("equiv", '\u2261');
284 entities.Add ("le", '\u2264');
285 entities.Add ("ge", '\u2265');
286 entities.Add ("sub", '\u2282');
287 entities.Add ("sup", '\u2283');
288 entities.Add ("nsub", '\u2284');
289 entities.Add ("sube", '\u2286');
290 entities.Add ("supe", '\u2287');
291 entities.Add ("oplus", '\u2295');
292 entities.Add ("otimes", '\u2297');
293 entities.Add ("perp", '\u22A5');
294 entities.Add ("sdot", '\u22C5');
295 entities.Add ("lceil", '\u2308');
296 entities.Add ("rceil", '\u2309');
297 entities.Add ("lfloor", '\u230A');
298 entities.Add ("rfloor", '\u230B');
299 entities.Add ("lang", '\u2329');
300 entities.Add ("rang", '\u232A');
301 entities.Add ("loz", '\u25CA');
302 entities.Add ("spades", '\u2660');
303 entities.Add ("clubs", '\u2663');
304 entities.Add ("hearts", '\u2665');
305 entities.Add ("diams", '\u2666');
306 entities.Add ("quot", '\u0022');
307 entities.Add ("amp", '\u0026');
308 entities.Add ("lt", '\u003C');
309 entities.Add ("gt", '\u003E');
310 entities.Add ("OElig", '\u0152');
311 entities.Add ("oelig", '\u0153');
312 entities.Add ("Scaron", '\u0160');
313 entities.Add ("scaron", '\u0161');
314 entities.Add ("Yuml", '\u0178');
315 entities.Add ("circ", '\u02C6');
316 entities.Add ("tilde", '\u02DC');
317 entities.Add ("ensp", '\u2002');
318 entities.Add ("emsp", '\u2003');
319 entities.Add ("thinsp", '\u2009');
320 entities.Add ("zwnj", '\u200C');
321 entities.Add ("zwj", '\u200D');
322 entities.Add ("lrm", '\u200E');
323 entities.Add ("rlm", '\u200F');
324 entities.Add ("ndash", '\u2013');
325 entities.Add ("mdash", '\u2014');
326 entities.Add ("lsquo", '\u2018');
327 entities.Add ("rsquo", '\u2019');
328 entities.Add ("sbquo", '\u201A');
329 entities.Add ("ldquo", '\u201C');
330 entities.Add ("rdquo", '\u201D');
331 entities.Add ("bdquo", '\u201E');
332 entities.Add ("dagger", '\u2020');
333 entities.Add ("Dagger", '\u2021');
334 entities.Add ("permil", '\u2030');
335 entities.Add ("lsaquo", '\u2039');
336 entities.Add ("rsaquo", '\u203A');
337 entities.Add ("euro", '\u20AC');
340 public HttpUtility ()
344 #endregion // Constructors
348 public static void HtmlAttributeEncode (string s, TextWriter output)
350 output.Write(HtmlAttributeEncode(s));
353 public static string HtmlAttributeEncode (string s)
358 bool needEncode = false;
359 for (int i = 0; i < s.Length; i++) {
360 if (s [i] == '&' || s [i] == '"' || s [i] == '<') {
369 StringBuilder output = new StringBuilder ();
371 for (int i = 0; i < len; i++)
374 output.Append ("&");
377 output.Append (""");
380 output.Append ("<");
383 output.Append (s [i]);
387 return output.ToString();
390 public static string UrlDecode (string str)
392 return UrlDecode(str, Encoding.UTF8);
395 static char [] GetChars (MemoryStream b, Encoding e)
397 return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
400 static void WriteCharBytes (IList buf, char ch, Encoding e)
403 foreach (byte b in e.GetBytes (new char[] { ch }))
409 public static string UrlDecode (string s, Encoding e)
414 if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
421 var bytes = new List <byte> ();
425 for (int i = 0; i < len; i++) {
427 if (ch == '%' && i + 2 < len && s [i + 1] != '%') {
428 if (s [i + 1] == 'u' && i + 5 < len) {
429 // unicode hex sequence
430 xchar = GetChar (s, i + 2, 4);
432 WriteCharBytes (bytes, (char)xchar, e);
435 WriteCharBytes (bytes, '%', e);
436 } else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
437 WriteCharBytes (bytes, (char)xchar, e);
440 WriteCharBytes (bytes, '%', e);
446 WriteCharBytes (bytes, ' ', e);
448 WriteCharBytes (bytes, ch, e);
451 byte[] buf = bytes.ToArray ();
453 return e.GetString (buf);
457 public static string UrlDecode (byte [] bytes, Encoding e)
462 return UrlDecode (bytes, 0, bytes.Length, e);
465 static int GetInt (byte b)
468 if (c >= '0' && c <= '9')
471 if (c >= 'a' && c <= 'f')
474 if (c >= 'A' && c <= 'F')
480 static int GetChar (byte [] bytes, int offset, int length)
483 int end = length + offset;
484 for (int i = offset; i < end; i++) {
485 int current = GetInt (bytes [i]);
488 value = (value << 4) + current;
494 static int GetChar (string str, int offset, int length)
497 int end = length + offset;
498 for (int i = offset; i < end; i++) {
503 int current = GetInt ((byte) c);
506 val = (val << 4) + current;
512 public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
520 throw new ArgumentNullException ("bytes");
522 if (offset < 0 || offset > bytes.Length)
523 throw new ArgumentOutOfRangeException ("offset");
525 if (count < 0 || offset + count > bytes.Length)
526 throw new ArgumentOutOfRangeException ("count");
528 StringBuilder output = new StringBuilder ();
529 MemoryStream acc = new MemoryStream ();
531 int end = count + offset;
533 for (int i = offset; i < end; i++) {
534 if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
535 if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
536 if (acc.Length > 0) {
537 output.Append (GetChars (acc, e));
540 xchar = GetChar (bytes, i + 2, 4);
542 output.Append ((char) xchar);
546 } else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
547 acc.WriteByte ((byte) xchar);
553 if (acc.Length > 0) {
554 output.Append (GetChars (acc, e));
558 if (bytes [i] == '+') {
561 output.Append ((char) bytes [i]);
565 if (acc.Length > 0) {
566 output.Append (GetChars (acc, e));
570 return output.ToString ();
573 public static byte [] UrlDecodeToBytes (byte [] bytes)
578 return UrlDecodeToBytes (bytes, 0, bytes.Length);
581 public static byte [] UrlDecodeToBytes (string str)
583 return UrlDecodeToBytes (str, Encoding.UTF8);
586 public static byte [] UrlDecodeToBytes (string str, Encoding e)
592 throw new ArgumentNullException ("e");
594 return UrlDecodeToBytes (e.GetBytes (str));
597 public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
604 int len = bytes.Length;
605 if (offset < 0 || offset >= len)
606 throw new ArgumentOutOfRangeException("offset");
608 if (count < 0 || offset > len - count)
609 throw new ArgumentOutOfRangeException("count");
611 MemoryStream result = new MemoryStream ();
612 int end = offset + count;
613 for (int i = offset; i < end; i++){
614 char c = (char) bytes [i];
617 } else if (c == '%' && i < end - 2) {
618 int xchar = GetChar (bytes, i + 1, 2);
624 result.WriteByte ((byte) c);
627 return result.ToArray ();
630 public static string UrlEncode(string str)
632 return UrlEncode(str, Encoding.UTF8);
635 public static string UrlEncode (string s, Encoding Enc)
643 bool needEncode = false;
645 for (int i = 0; i < len; i++) {
647 if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) {
659 // avoided GetByteCount call
660 byte [] bytes = new byte[Enc.GetMaxByteCount(s.Length)];
661 int realLen = Enc.GetBytes (s, 0, s.Length, bytes, 0);
662 return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, realLen));
665 public static string UrlEncode (byte [] bytes)
670 if (bytes.Length == 0)
673 return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
676 public static string UrlEncode (byte [] bytes, int offset, int count)
681 if (bytes.Length == 0)
684 return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, offset, count));
687 public static byte [] UrlEncodeToBytes (string str)
689 return UrlEncodeToBytes (str, Encoding.UTF8);
692 public static byte [] UrlEncodeToBytes (string str, Encoding e)
700 byte [] bytes = e.GetBytes (str);
701 return UrlEncodeToBytes (bytes, 0, bytes.Length);
704 public static byte [] UrlEncodeToBytes (byte [] bytes)
709 if (bytes.Length == 0)
712 return UrlEncodeToBytes (bytes, 0, bytes.Length);
715 static char [] hexChars = "0123456789abcdef".ToCharArray ();
717 static bool NotEncoded (char c)
719 return (c == '!' || c == '\'' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_');
722 static void UrlEncodeChar (char c, Stream result, bool isUnicode) {
724 //FIXME: what happens when there is an internal error?
726 // throw new ArgumentOutOfRangeException ("c", c, "c must be less than 256");
730 result.WriteByte ((byte)'%');
731 result.WriteByte ((byte)'u');
733 result.WriteByte ((byte)hexChars [idx]);
734 idx = (i >> 8) & 0x0F;
735 result.WriteByte ((byte)hexChars [idx]);
736 idx = (i >> 4) & 0x0F;
737 result.WriteByte ((byte)hexChars [idx]);
739 result.WriteByte ((byte)hexChars [idx]);
743 if (c > ' ' && NotEncoded (c)) {
744 result.WriteByte ((byte)c);
748 result.WriteByte ((byte)'+');
752 (c < 'A' && c > '9') ||
753 (c > 'Z' && c < 'a') ||
755 if (isUnicode && c > 127) {
756 result.WriteByte ((byte)'%');
757 result.WriteByte ((byte)'u');
758 result.WriteByte ((byte)'0');
759 result.WriteByte ((byte)'0');
762 result.WriteByte ((byte)'%');
764 int idx = ((int) c) >> 4;
765 result.WriteByte ((byte)hexChars [idx]);
766 idx = ((int) c) & 0x0F;
767 result.WriteByte ((byte)hexChars [idx]);
770 result.WriteByte ((byte)c);
773 public static byte [] UrlEncodeToBytes (byte [] bytes, int offset, int count)
778 int len = bytes.Length;
782 if (offset < 0 || offset >= len)
783 throw new ArgumentOutOfRangeException("offset");
785 if (count < 0 || count > len - offset)
786 throw new ArgumentOutOfRangeException("count");
788 MemoryStream result = new MemoryStream (count);
789 int end = offset + count;
790 for (int i = offset; i < end; i++)
791 UrlEncodeChar ((char)bytes [i], result, false);
793 return result.ToArray();
796 public static string UrlEncodeUnicode (string str)
801 return Encoding.ASCII.GetString (UrlEncodeUnicodeToBytes (str));
804 public static byte [] UrlEncodeUnicodeToBytes (string str)
812 MemoryStream result = new MemoryStream (str.Length);
813 foreach (char c in str){
814 UrlEncodeChar (c, result, true);
816 return result.ToArray ();
820 /// Decodes an HTML-encoded string and returns the decoded string.
822 /// <param name="s">The HTML string to decode. </param>
823 /// <returns>The decoded text.</returns>
824 public static string HtmlDecode (string s)
827 throw new ArgumentNullException ("s");
829 if (s.IndexOf ('&') == -1)
832 StringBuilder entity = new StringBuilder ();
833 StringBuilder output = new StringBuilder ();
836 // 1 -> right after '&'
837 // 2 -> between '&' and ';' but no '#'
838 // 3 -> '#' found after '&' and getting numbers
841 bool have_trailing_digits = false;
843 for (int i = 0; i < len; i++) {
857 if (have_trailing_digits) {
858 entity.Append (number.ToString (CultureInfo.InvariantCulture));
859 have_trailing_digits = false;
862 output.Append (entity.ToString ());
871 output.Append (entity.ToString ());
883 } else if (state == 2) {
886 string key = entity.ToString ();
887 if (key.Length > 1 && Entities.ContainsKey (key.Substring (1, key.Length - 2)))
888 key = Entities [key.Substring (1, key.Length - 2)].ToString ();
894 } else if (state == 3) {
896 if (number > 65535) {
897 output.Append ("&#");
898 output.Append (number.ToString (CultureInfo.InvariantCulture));
901 output.Append ((char) number);
905 have_trailing_digits = false;
906 } else if (Char.IsDigit (c)) {
907 number = number * 10 + ((int) c - '0');
908 have_trailing_digits = true;
911 if (have_trailing_digits) {
912 entity.Append (number.ToString (CultureInfo.InvariantCulture));
913 have_trailing_digits = false;
920 if (entity.Length > 0) {
921 output.Append (entity.ToString ());
922 } else if (have_trailing_digits) {
923 output.Append (number.ToString (CultureInfo.InvariantCulture));
925 return output.ToString ();
929 /// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.
931 /// <param name="s">The HTML string to decode</param>
932 /// <param name="output">The TextWriter output stream containing the decoded string. </param>
933 public static void HtmlDecode(string s, TextWriter output)
936 output.Write (HtmlDecode (s));
940 /// HTML-encodes a string and returns the encoded string.
942 /// <param name="s">The text string to encode. </param>
943 /// <returns>The HTML-encoded text.</returns>
944 public static string HtmlEncode (string s)
949 bool needEncode = false;
950 for (int i = 0; i < s.Length; i++) {
952 if (c == '&' || c == '"' || c == '<' || c == '>' || c > 159) {
961 StringBuilder output = new StringBuilder ();
964 for (int i = 0; i < len; i++)
967 output.Append ("&");
970 output.Append (">");
973 output.Append ("<");
976 output.Append (""");
979 // MS starts encoding with &# from 160 and stops at 255.
980 // We don't do that. One reason is the 65308/65310 unicode
981 // characters that look like '<' and '>'.
983 if (s [i] > 159 && s [i] < 256) {
987 output.Append ("&#");
988 output.Append (((int) s [i]).ToString (CultureInfo.InvariantCulture));
991 output.Append (s [i]);
995 return output.ToString ();
999 /// HTML-encodes a string and sends the resulting output to a TextWriter output stream.
1001 /// <param name="s">The string to encode. </param>
1002 /// <param name="output">The TextWriter output stream containing the encoded string. </param>
1003 public static void HtmlEncode(string s, TextWriter output)
1006 output.Write (HtmlEncode (s));
1009 public static string UrlPathEncode (string s)
1011 if (s == null || s.Length == 0)
1014 MemoryStream result = new MemoryStream ();
1015 int length = s.Length;
1016 for (int i = 0; i < length; i++) {
1017 UrlPathEncodeChar (s [i], result);
1019 return Encoding.ASCII.GetString (result.ToArray ());
1022 static void UrlPathEncodeChar (char c, Stream result)
1024 if (c < 33 || c > 126) {
1025 byte [] bIn = Encoding.UTF8.GetBytes (c.ToString ());
1026 for (int i = 0; i < bIn.Length; i++) {
1027 result.WriteByte ((byte) '%');
1028 int idx = ((int) bIn [i]) >> 4;
1029 result.WriteByte ((byte) hexChars [idx]);
1030 idx = ((int) bIn [i]) & 0x0F;
1031 result.WriteByte ((byte) hexChars [idx]);
1034 else if (c == ' ') {
1035 result.WriteByte ((byte) '%');
1036 result.WriteByte ((byte) '2');
1037 result.WriteByte ((byte) '0');
1040 result.WriteByte ((byte) c);
1043 public static NameValueCollection ParseQueryString (string query)
1045 return ParseQueryString (query, Encoding.UTF8);
1048 public static NameValueCollection ParseQueryString (string query, Encoding encoding)
1051 throw new ArgumentNullException ("query");
1052 if (encoding == null)
1053 throw new ArgumentNullException ("encoding");
1054 if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))
1055 return new NameValueCollection ();
1056 if (query[0] == '?')
1057 query = query.Substring (1);
1059 NameValueCollection result = new HttpQSCollection ();
1060 ParseQueryString (query, encoding, result);
1064 internal static void ParseQueryString (string query, Encoding encoding, NameValueCollection result)
1066 if (query.Length == 0)
1069 string decoded = HtmlDecode (query);
1070 int decodedLength = decoded.Length;
1073 while (namePos <= decodedLength) {
1074 int valuePos = -1, valueEnd = -1;
1075 for (int q = namePos; q < decodedLength; q++) {
1076 if (valuePos == -1 && decoded [q] == '=') {
1078 } else if (decoded [q] == '&') {
1086 if (decoded [namePos] == '?')
1091 if (valuePos == -1) {
1095 name = UrlDecode (decoded.Substring (namePos, valuePos - namePos - 1), encoding);
1099 valueEnd = decoded.Length;
1101 namePos = valueEnd + 1;
1103 value = UrlDecode (decoded.Substring (valuePos, valueEnd - valuePos), encoding);
1105 result.Add (name, value);
1110 #endregion // Methods