2 // System.Web.HttpUtility
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 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.Specialized;
34 using System.Globalization;
36 using System.Security.Permissions;
38 using System.Web.Util;
40 namespace System.Web {
42 // CAS - no InheritanceDemand here as the class is sealed
43 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
44 public sealed class HttpUtility {
47 static Hashtable entities;
48 static object lock_ = new object ();
52 static Hashtable Entities {
65 static void InitEntities ()
67 // Build the hash table of HTML entity references. This list comes
68 // from the HTML 4.01 W3C recommendation.
69 entities = new Hashtable ();
70 entities.Add ("nbsp", '\u00A0');
71 entities.Add ("iexcl", '\u00A1');
72 entities.Add ("cent", '\u00A2');
73 entities.Add ("pound", '\u00A3');
74 entities.Add ("curren", '\u00A4');
75 entities.Add ("yen", '\u00A5');
76 entities.Add ("brvbar", '\u00A6');
77 entities.Add ("sect", '\u00A7');
78 entities.Add ("uml", '\u00A8');
79 entities.Add ("copy", '\u00A9');
80 entities.Add ("ordf", '\u00AA');
81 entities.Add ("laquo", '\u00AB');
82 entities.Add ("not", '\u00AC');
83 entities.Add ("shy", '\u00AD');
84 entities.Add ("reg", '\u00AE');
85 entities.Add ("macr", '\u00AF');
86 entities.Add ("deg", '\u00B0');
87 entities.Add ("plusmn", '\u00B1');
88 entities.Add ("sup2", '\u00B2');
89 entities.Add ("sup3", '\u00B3');
90 entities.Add ("acute", '\u00B4');
91 entities.Add ("micro", '\u00B5');
92 entities.Add ("para", '\u00B6');
93 entities.Add ("middot", '\u00B7');
94 entities.Add ("cedil", '\u00B8');
95 entities.Add ("sup1", '\u00B9');
96 entities.Add ("ordm", '\u00BA');
97 entities.Add ("raquo", '\u00BB');
98 entities.Add ("frac14", '\u00BC');
99 entities.Add ("frac12", '\u00BD');
100 entities.Add ("frac34", '\u00BE');
101 entities.Add ("iquest", '\u00BF');
102 entities.Add ("Agrave", '\u00C0');
103 entities.Add ("Aacute", '\u00C1');
104 entities.Add ("Acirc", '\u00C2');
105 entities.Add ("Atilde", '\u00C3');
106 entities.Add ("Auml", '\u00C4');
107 entities.Add ("Aring", '\u00C5');
108 entities.Add ("AElig", '\u00C6');
109 entities.Add ("Ccedil", '\u00C7');
110 entities.Add ("Egrave", '\u00C8');
111 entities.Add ("Eacute", '\u00C9');
112 entities.Add ("Ecirc", '\u00CA');
113 entities.Add ("Euml", '\u00CB');
114 entities.Add ("Igrave", '\u00CC');
115 entities.Add ("Iacute", '\u00CD');
116 entities.Add ("Icirc", '\u00CE');
117 entities.Add ("Iuml", '\u00CF');
118 entities.Add ("ETH", '\u00D0');
119 entities.Add ("Ntilde", '\u00D1');
120 entities.Add ("Ograve", '\u00D2');
121 entities.Add ("Oacute", '\u00D3');
122 entities.Add ("Ocirc", '\u00D4');
123 entities.Add ("Otilde", '\u00D5');
124 entities.Add ("Ouml", '\u00D6');
125 entities.Add ("times", '\u00D7');
126 entities.Add ("Oslash", '\u00D8');
127 entities.Add ("Ugrave", '\u00D9');
128 entities.Add ("Uacute", '\u00DA');
129 entities.Add ("Ucirc", '\u00DB');
130 entities.Add ("Uuml", '\u00DC');
131 entities.Add ("Yacute", '\u00DD');
132 entities.Add ("THORN", '\u00DE');
133 entities.Add ("szlig", '\u00DF');
134 entities.Add ("agrave", '\u00E0');
135 entities.Add ("aacute", '\u00E1');
136 entities.Add ("acirc", '\u00E2');
137 entities.Add ("atilde", '\u00E3');
138 entities.Add ("auml", '\u00E4');
139 entities.Add ("aring", '\u00E5');
140 entities.Add ("aelig", '\u00E6');
141 entities.Add ("ccedil", '\u00E7');
142 entities.Add ("egrave", '\u00E8');
143 entities.Add ("eacute", '\u00E9');
144 entities.Add ("ecirc", '\u00EA');
145 entities.Add ("euml", '\u00EB');
146 entities.Add ("igrave", '\u00EC');
147 entities.Add ("iacute", '\u00ED');
148 entities.Add ("icirc", '\u00EE');
149 entities.Add ("iuml", '\u00EF');
150 entities.Add ("eth", '\u00F0');
151 entities.Add ("ntilde", '\u00F1');
152 entities.Add ("ograve", '\u00F2');
153 entities.Add ("oacute", '\u00F3');
154 entities.Add ("ocirc", '\u00F4');
155 entities.Add ("otilde", '\u00F5');
156 entities.Add ("ouml", '\u00F6');
157 entities.Add ("divide", '\u00F7');
158 entities.Add ("oslash", '\u00F8');
159 entities.Add ("ugrave", '\u00F9');
160 entities.Add ("uacute", '\u00FA');
161 entities.Add ("ucirc", '\u00FB');
162 entities.Add ("uuml", '\u00FC');
163 entities.Add ("yacute", '\u00FD');
164 entities.Add ("thorn", '\u00FE');
165 entities.Add ("yuml", '\u00FF');
166 entities.Add ("fnof", '\u0192');
167 entities.Add ("Alpha", '\u0391');
168 entities.Add ("Beta", '\u0392');
169 entities.Add ("Gamma", '\u0393');
170 entities.Add ("Delta", '\u0394');
171 entities.Add ("Epsilon", '\u0395');
172 entities.Add ("Zeta", '\u0396');
173 entities.Add ("Eta", '\u0397');
174 entities.Add ("Theta", '\u0398');
175 entities.Add ("Iota", '\u0399');
176 entities.Add ("Kappa", '\u039A');
177 entities.Add ("Lambda", '\u039B');
178 entities.Add ("Mu", '\u039C');
179 entities.Add ("Nu", '\u039D');
180 entities.Add ("Xi", '\u039E');
181 entities.Add ("Omicron", '\u039F');
182 entities.Add ("Pi", '\u03A0');
183 entities.Add ("Rho", '\u03A1');
184 entities.Add ("Sigma", '\u03A3');
185 entities.Add ("Tau", '\u03A4');
186 entities.Add ("Upsilon", '\u03A5');
187 entities.Add ("Phi", '\u03A6');
188 entities.Add ("Chi", '\u03A7');
189 entities.Add ("Psi", '\u03A8');
190 entities.Add ("Omega", '\u03A9');
191 entities.Add ("alpha", '\u03B1');
192 entities.Add ("beta", '\u03B2');
193 entities.Add ("gamma", '\u03B3');
194 entities.Add ("delta", '\u03B4');
195 entities.Add ("epsilon", '\u03B5');
196 entities.Add ("zeta", '\u03B6');
197 entities.Add ("eta", '\u03B7');
198 entities.Add ("theta", '\u03B8');
199 entities.Add ("iota", '\u03B9');
200 entities.Add ("kappa", '\u03BA');
201 entities.Add ("lambda", '\u03BB');
202 entities.Add ("mu", '\u03BC');
203 entities.Add ("nu", '\u03BD');
204 entities.Add ("xi", '\u03BE');
205 entities.Add ("omicron", '\u03BF');
206 entities.Add ("pi", '\u03C0');
207 entities.Add ("rho", '\u03C1');
208 entities.Add ("sigmaf", '\u03C2');
209 entities.Add ("sigma", '\u03C3');
210 entities.Add ("tau", '\u03C4');
211 entities.Add ("upsilon", '\u03C5');
212 entities.Add ("phi", '\u03C6');
213 entities.Add ("chi", '\u03C7');
214 entities.Add ("psi", '\u03C8');
215 entities.Add ("omega", '\u03C9');
216 entities.Add ("thetasym", '\u03D1');
217 entities.Add ("upsih", '\u03D2');
218 entities.Add ("piv", '\u03D6');
219 entities.Add ("bull", '\u2022');
220 entities.Add ("hellip", '\u2026');
221 entities.Add ("prime", '\u2032');
222 entities.Add ("Prime", '\u2033');
223 entities.Add ("oline", '\u203E');
224 entities.Add ("frasl", '\u2044');
225 entities.Add ("weierp", '\u2118');
226 entities.Add ("image", '\u2111');
227 entities.Add ("real", '\u211C');
228 entities.Add ("trade", '\u2122');
229 entities.Add ("alefsym", '\u2135');
230 entities.Add ("larr", '\u2190');
231 entities.Add ("uarr", '\u2191');
232 entities.Add ("rarr", '\u2192');
233 entities.Add ("darr", '\u2193');
234 entities.Add ("harr", '\u2194');
235 entities.Add ("crarr", '\u21B5');
236 entities.Add ("lArr", '\u21D0');
237 entities.Add ("uArr", '\u21D1');
238 entities.Add ("rArr", '\u21D2');
239 entities.Add ("dArr", '\u21D3');
240 entities.Add ("hArr", '\u21D4');
241 entities.Add ("forall", '\u2200');
242 entities.Add ("part", '\u2202');
243 entities.Add ("exist", '\u2203');
244 entities.Add ("empty", '\u2205');
245 entities.Add ("nabla", '\u2207');
246 entities.Add ("isin", '\u2208');
247 entities.Add ("notin", '\u2209');
248 entities.Add ("ni", '\u220B');
249 entities.Add ("prod", '\u220F');
250 entities.Add ("sum", '\u2211');
251 entities.Add ("minus", '\u2212');
252 entities.Add ("lowast", '\u2217');
253 entities.Add ("radic", '\u221A');
254 entities.Add ("prop", '\u221D');
255 entities.Add ("infin", '\u221E');
256 entities.Add ("ang", '\u2220');
257 entities.Add ("and", '\u2227');
258 entities.Add ("or", '\u2228');
259 entities.Add ("cap", '\u2229');
260 entities.Add ("cup", '\u222A');
261 entities.Add ("int", '\u222B');
262 entities.Add ("there4", '\u2234');
263 entities.Add ("sim", '\u223C');
264 entities.Add ("cong", '\u2245');
265 entities.Add ("asymp", '\u2248');
266 entities.Add ("ne", '\u2260');
267 entities.Add ("equiv", '\u2261');
268 entities.Add ("le", '\u2264');
269 entities.Add ("ge", '\u2265');
270 entities.Add ("sub", '\u2282');
271 entities.Add ("sup", '\u2283');
272 entities.Add ("nsub", '\u2284');
273 entities.Add ("sube", '\u2286');
274 entities.Add ("supe", '\u2287');
275 entities.Add ("oplus", '\u2295');
276 entities.Add ("otimes", '\u2297');
277 entities.Add ("perp", '\u22A5');
278 entities.Add ("sdot", '\u22C5');
279 entities.Add ("lceil", '\u2308');
280 entities.Add ("rceil", '\u2309');
281 entities.Add ("lfloor", '\u230A');
282 entities.Add ("rfloor", '\u230B');
283 entities.Add ("lang", '\u2329');
284 entities.Add ("rang", '\u232A');
285 entities.Add ("loz", '\u25CA');
286 entities.Add ("spades", '\u2660');
287 entities.Add ("clubs", '\u2663');
288 entities.Add ("hearts", '\u2665');
289 entities.Add ("diams", '\u2666');
290 entities.Add ("quot", '\u0022');
291 entities.Add ("amp", '\u0026');
292 entities.Add ("lt", '\u003C');
293 entities.Add ("gt", '\u003E');
294 entities.Add ("OElig", '\u0152');
295 entities.Add ("oelig", '\u0153');
296 entities.Add ("Scaron", '\u0160');
297 entities.Add ("scaron", '\u0161');
298 entities.Add ("Yuml", '\u0178');
299 entities.Add ("circ", '\u02C6');
300 entities.Add ("tilde", '\u02DC');
301 entities.Add ("ensp", '\u2002');
302 entities.Add ("emsp", '\u2003');
303 entities.Add ("thinsp", '\u2009');
304 entities.Add ("zwnj", '\u200C');
305 entities.Add ("zwj", '\u200D');
306 entities.Add ("lrm", '\u200E');
307 entities.Add ("rlm", '\u200F');
308 entities.Add ("ndash", '\u2013');
309 entities.Add ("mdash", '\u2014');
310 entities.Add ("lsquo", '\u2018');
311 entities.Add ("rsquo", '\u2019');
312 entities.Add ("sbquo", '\u201A');
313 entities.Add ("ldquo", '\u201C');
314 entities.Add ("rdquo", '\u201D');
315 entities.Add ("bdquo", '\u201E');
316 entities.Add ("dagger", '\u2020');
317 entities.Add ("Dagger", '\u2021');
318 entities.Add ("permil", '\u2030');
319 entities.Add ("lsaquo", '\u2039');
320 entities.Add ("rsaquo", '\u203A');
321 entities.Add ("euro", '\u20AC');
324 public HttpUtility ()
328 #endregion // Constructors
332 public static void HtmlAttributeEncode (string s, TextWriter output)
334 output.Write(HtmlAttributeEncode(s));
337 public static string HtmlAttributeEncode (string s)
342 bool needEncode = false;
343 for (int i = 0; i < s.Length; i++) {
344 if (s [i] == '&' || s [i] == '"' || s [i] == '<') {
353 StringBuilder output = new StringBuilder ();
355 for (int i = 0; i < len; i++)
358 output.Append ("&");
361 output.Append (""");
364 output.Append ("<");
367 output.Append (s [i]);
371 return output.ToString();
374 public static string UrlDecode (string str)
376 return UrlDecode(str, Encoding.UTF8);
379 private static char [] GetChars (MemoryStream b, Encoding e)
381 return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
384 public static string UrlDecode (string s, Encoding e)
389 if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
395 StringBuilder output = new StringBuilder ();
397 MemoryStream bytes = new MemoryStream ();
400 for (int i = 0; i < len; i++) {
401 if (s [i] == '%' && i + 2 < len && s [i + 1] != '%') {
402 if (s [i + 1] == 'u' && i + 5 < len) {
403 if (bytes.Length > 0) {
404 output.Append (GetChars (bytes, e));
408 xchar = GetChar (s, i + 2, 4);
410 output.Append ((char) xchar);
415 } else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
416 bytes.WriteByte ((byte) xchar);
424 if (bytes.Length > 0) {
425 output.Append (GetChars (bytes, e));
432 output.Append (s [i]);
436 if (bytes.Length > 0) {
437 output.Append (GetChars (bytes, e));
441 return output.ToString ();
444 public static string UrlDecode (byte [] bytes, Encoding e)
449 return UrlDecode (bytes, 0, bytes.Length, e);
452 private static int GetInt (byte b)
455 if (c >= '0' && c <= '9')
458 if (c >= 'a' && c <= 'f')
461 if (c >= 'A' && c <= 'F')
467 private static int GetChar (byte [] bytes, int offset, int length)
470 int end = length + offset;
471 for (int i = offset; i < end; i++) {
472 int current = GetInt (bytes [i]);
475 value = (value << 4) + current;
481 private static int GetChar (string str, int offset, int length)
484 int end = length + offset;
485 for (int i = offset; i < end; i++) {
490 int current = GetInt ((byte) c);
493 val = (val << 4) + current;
499 public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
507 throw new ArgumentNullException ("bytes");
509 if (offset < 0 || offset > bytes.Length)
510 throw new ArgumentOutOfRangeException ("offset");
512 if (count < 0 || offset + count > bytes.Length)
513 throw new ArgumentOutOfRangeException ("count");
515 StringBuilder output = new StringBuilder ();
516 MemoryStream acc = new MemoryStream ();
518 int end = count + offset;
520 for (int i = offset; i < end; i++) {
521 if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
522 if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
523 if (acc.Length > 0) {
524 output.Append (GetChars (acc, e));
527 xchar = GetChar (bytes, i + 2, 4);
529 output.Append ((char) xchar);
533 } else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
534 acc.WriteByte ((byte) xchar);
540 if (acc.Length > 0) {
541 output.Append (GetChars (acc, e));
545 if (bytes [i] == '+') {
548 output.Append ((char) bytes [i]);
552 if (acc.Length > 0) {
553 output.Append (GetChars (acc, e));
557 return output.ToString ();
560 public static byte [] UrlDecodeToBytes (byte [] bytes)
565 return UrlDecodeToBytes (bytes, 0, bytes.Length);
568 public static byte [] UrlDecodeToBytes (string str)
570 return UrlDecodeToBytes (str, Encoding.UTF8);
573 public static byte [] UrlDecodeToBytes (string str, Encoding e)
579 throw new ArgumentNullException ("e");
581 return UrlDecodeToBytes (e.GetBytes (str));
584 public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
591 int len = bytes.Length;
592 if (offset < 0 || offset >= len)
593 throw new ArgumentOutOfRangeException("offset");
595 if (count < 0 || offset > len - count)
596 throw new ArgumentOutOfRangeException("count");
598 MemoryStream result = new MemoryStream ();
599 int end = offset + count;
600 for (int i = offset; i < end; i++){
601 char c = (char) bytes [i];
604 } else if (c == '%' && i < end - 2) {
605 int xchar = GetChar (bytes, i + 1, 2);
611 result.WriteByte ((byte) c);
614 return result.ToArray ();
617 public static string UrlEncode(string str)
619 return UrlEncode(str, Encoding.UTF8);
622 public static string UrlEncode (string s, Encoding Enc)
630 bool needEncode = false;
632 for (int i = 0; i < len; i++) {
634 if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) {
646 // avoided GetByteCount call
647 byte [] bytes = new byte[Enc.GetMaxByteCount(s.Length)];
648 int realLen = Enc.GetBytes (s, 0, s.Length, bytes, 0);
649 return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, realLen));
652 public static string UrlEncode (byte [] bytes)
657 if (bytes.Length == 0)
660 return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
663 public static string UrlEncode (byte [] bytes, int offset, int count)
668 if (bytes.Length == 0)
671 return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, offset, count));
674 public static byte [] UrlEncodeToBytes (string str)
676 return UrlEncodeToBytes (str, Encoding.UTF8);
679 public static byte [] UrlEncodeToBytes (string str, Encoding e)
687 byte [] bytes = e.GetBytes (str);
688 return UrlEncodeToBytes (bytes, 0, bytes.Length);
691 public static byte [] UrlEncodeToBytes (byte [] bytes)
696 if (bytes.Length == 0)
699 return UrlEncodeToBytes (bytes, 0, bytes.Length);
702 static char [] hexChars = "0123456789abcdef".ToCharArray ();
704 static bool NotEncoded (char c)
706 return (c == '!' || c == '\'' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_');
709 static void UrlEncodeChar (char c, Stream result, bool isUnicode) {
711 //FIXME: what happens when there is an internal error?
713 // throw new ArgumentOutOfRangeException ("c", c, "c must be less than 256");
717 result.WriteByte ((byte)'%');
718 result.WriteByte ((byte)'u');
720 result.WriteByte ((byte)hexChars [idx]);
721 idx = (i >> 8) & 0x0F;
722 result.WriteByte ((byte)hexChars [idx]);
723 idx = (i >> 4) & 0x0F;
724 result.WriteByte ((byte)hexChars [idx]);
726 result.WriteByte ((byte)hexChars [idx]);
730 if (c > ' ' && NotEncoded (c)) {
731 result.WriteByte ((byte)c);
735 result.WriteByte ((byte)'+');
739 (c < 'A' && c > '9') ||
740 (c > 'Z' && c < 'a') ||
742 if (isUnicode && c > 127) {
743 result.WriteByte ((byte)'%');
744 result.WriteByte ((byte)'u');
745 result.WriteByte ((byte)'0');
746 result.WriteByte ((byte)'0');
749 result.WriteByte ((byte)'%');
751 int idx = ((int) c) >> 4;
752 result.WriteByte ((byte)hexChars [idx]);
753 idx = ((int) c) & 0x0F;
754 result.WriteByte ((byte)hexChars [idx]);
757 result.WriteByte ((byte)c);
760 public static byte [] UrlEncodeToBytes (byte [] bytes, int offset, int count)
765 int len = bytes.Length;
769 if (offset < 0 || offset >= len)
770 throw new ArgumentOutOfRangeException("offset");
772 if (count < 0 || count > len - offset)
773 throw new ArgumentOutOfRangeException("count");
775 MemoryStream result = new MemoryStream (count);
776 int end = offset + count;
777 for (int i = offset; i < end; i++)
778 UrlEncodeChar ((char)bytes [i], result, false);
780 return result.ToArray();
783 public static string UrlEncodeUnicode (string str)
788 return Encoding.ASCII.GetString (UrlEncodeUnicodeToBytes (str));
791 public static byte [] UrlEncodeUnicodeToBytes (string str)
799 MemoryStream result = new MemoryStream (str.Length);
800 foreach (char c in str){
801 UrlEncodeChar (c, result, true);
803 return result.ToArray ();
807 /// Decodes an HTML-encoded string and returns the decoded string.
809 /// <param name="s">The HTML string to decode. </param>
810 /// <returns>The decoded text.</returns>
811 public static string HtmlDecode (string s)
814 throw new ArgumentNullException ("s");
816 if (s.IndexOf ('&') == -1)
819 StringBuilder entity = new StringBuilder ();
820 StringBuilder output = new StringBuilder ();
823 // 1 -> right after '&'
824 // 2 -> between '&' and ';' but no '#'
825 // 3 -> '#' found after '&' and getting numbers
828 bool have_trailing_digits = false;
830 for (int i = 0; i < len; i++) {
844 if (have_trailing_digits) {
845 entity.Append (number.ToString (CultureInfo.InvariantCulture));
846 have_trailing_digits = false;
849 output.Append (entity.ToString ());
858 output.Append (entity.ToString ());
870 } else if (state == 2) {
873 string key = entity.ToString ();
874 if (key.Length > 1 && Entities.ContainsKey (key.Substring (1, key.Length - 2)))
875 key = Entities [key.Substring (1, key.Length - 2)].ToString ();
881 } else if (state == 3) {
883 if (number > 65535) {
884 output.Append ("&#");
885 output.Append (number.ToString (CultureInfo.InvariantCulture));
888 output.Append ((char) number);
892 have_trailing_digits = false;
893 } else if (Char.IsDigit (c)) {
894 number = number * 10 + ((int) c - '0');
895 have_trailing_digits = true;
898 if (have_trailing_digits) {
899 entity.Append (number.ToString (CultureInfo.InvariantCulture));
900 have_trailing_digits = false;
907 if (entity.Length > 0) {
908 output.Append (entity.ToString ());
909 } else if (have_trailing_digits) {
910 output.Append (number.ToString (CultureInfo.InvariantCulture));
912 return output.ToString ();
916 /// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.
918 /// <param name="s">The HTML string to decode</param>
919 /// <param name="output">The TextWriter output stream containing the decoded string. </param>
920 public static void HtmlDecode(string s, TextWriter output)
923 output.Write (HtmlDecode (s));
927 /// HTML-encodes a string and returns the encoded string.
929 /// <param name="s">The text string to encode. </param>
930 /// <returns>The HTML-encoded text.</returns>
931 public static string HtmlEncode (string s)
936 bool needEncode = false;
937 for (int i = 0; i < s.Length; i++) {
939 if (c == '&' || c == '"' || c == '<' || c == '>' || c > 159) {
948 StringBuilder output = new StringBuilder ();
951 for (int i = 0; i < len; i++)
954 output.Append ("&");
957 output.Append (">");
960 output.Append ("<");
963 output.Append (""");
966 // MS starts encoding with &# from 160 and stops at 255.
967 // We don't do that. One reason is the 65308/65310 unicode
968 // characters that look like '<' and '>'.
970 if (s [i] > 159 && s [i] < 256) {
974 output.Append ("&#");
975 output.Append (((int) s [i]).ToString (CultureInfo.InvariantCulture));
978 output.Append (s [i]);
982 return output.ToString ();
986 /// HTML-encodes a string and sends the resulting output to a TextWriter output stream.
988 /// <param name="s">The string to encode. </param>
989 /// <param name="output">The TextWriter output stream containing the encoded string. </param>
990 public static void HtmlEncode(string s, TextWriter output)
993 output.Write (HtmlEncode (s));
997 public static string UrlPathEncode (string s)
999 if (s == null || s.Length == 0)
1002 MemoryStream result = new MemoryStream ();
1003 int length = s.Length;
1004 for (int i = 0; i < length; i++) {
1005 UrlPathEncodeChar (s [i], result);
1007 return Encoding.ASCII.GetString (result.ToArray ());
1010 static void UrlPathEncodeChar (char c, Stream result) {
1012 if (c < 33 || c > 126) {
1016 byte [] bIn = Encoding.UTF8.GetBytes (c.ToString ());
1017 for (int i = 0; i < bIn.Length; i++) {
1018 result.WriteByte ((byte) '%');
1019 int idx = ((int) bIn [i]) >> 4;
1020 result.WriteByte ((byte) hexChars [idx]);
1021 idx = ((int) bIn [i]) & 0x0F;
1022 result.WriteByte ((byte) hexChars [idx]);
1025 else if (c == ' ') {
1026 result.WriteByte ((byte) '%');
1027 result.WriteByte ((byte) '2');
1028 result.WriteByte ((byte) '0');
1031 result.WriteByte ((byte) c);
1036 public static NameValueCollection ParseQueryString (string query)
1038 return ParseQueryString (query, Encoding.UTF8);
1041 public static NameValueCollection ParseQueryString (string query, Encoding encoding)
1044 throw new ArgumentNullException ("query");
1045 if (encoding == null)
1046 throw new ArgumentNullException ("encoding");
1047 if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))
1048 return new NameValueCollection ();
1049 if (query[0] == '?')
1050 query = query.Substring (1);
1052 NameValueCollection result = new NameValueCollection ();
1053 ParseQueryString (query, encoding, result);
1058 internal static void ParseQueryString (string query, Encoding encoding, NameValueCollection result)
1060 if (query.Length == 0)
1065 while (namePos <= query.Length) {
1066 int valuePos = -1, valueEnd = -1;
1067 for (int q = namePos; q < query.Length; q++) {
1068 if (valuePos == -1 && query[q] == '=') {
1070 } else if (query[q] == '&') {
1078 if (query [namePos] == '?')
1083 if (valuePos == -1) {
1087 name = UrlDecode (query.Substring (namePos, valuePos - namePos - 1), encoding);
1091 valueEnd = query.Length;
1093 namePos = valueEnd + 1;
1095 value = UrlDecode (query.Substring (valuePos, valueEnd - valuePos), encoding);
1097 result.Add (name, value);
1102 #endregion // Methods