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 {
46 internal const char QueryParamSeparator = ';';
48 internal const char QueryParamSeparator = '&';
52 static Hashtable entities;
53 static object lock_ = new object ();
57 static Hashtable Entities {
70 static void InitEntities ()
72 // Build the hash table of HTML entity references. This list comes
73 // from the HTML 4.01 W3C recommendation.
74 entities = new Hashtable ();
75 entities.Add ("nbsp", '\u00A0');
76 entities.Add ("iexcl", '\u00A1');
77 entities.Add ("cent", '\u00A2');
78 entities.Add ("pound", '\u00A3');
79 entities.Add ("curren", '\u00A4');
80 entities.Add ("yen", '\u00A5');
81 entities.Add ("brvbar", '\u00A6');
82 entities.Add ("sect", '\u00A7');
83 entities.Add ("uml", '\u00A8');
84 entities.Add ("copy", '\u00A9');
85 entities.Add ("ordf", '\u00AA');
86 entities.Add ("laquo", '\u00AB');
87 entities.Add ("not", '\u00AC');
88 entities.Add ("shy", '\u00AD');
89 entities.Add ("reg", '\u00AE');
90 entities.Add ("macr", '\u00AF');
91 entities.Add ("deg", '\u00B0');
92 entities.Add ("plusmn", '\u00B1');
93 entities.Add ("sup2", '\u00B2');
94 entities.Add ("sup3", '\u00B3');
95 entities.Add ("acute", '\u00B4');
96 entities.Add ("micro", '\u00B5');
97 entities.Add ("para", '\u00B6');
98 entities.Add ("middot", '\u00B7');
99 entities.Add ("cedil", '\u00B8');
100 entities.Add ("sup1", '\u00B9');
101 entities.Add ("ordm", '\u00BA');
102 entities.Add ("raquo", '\u00BB');
103 entities.Add ("frac14", '\u00BC');
104 entities.Add ("frac12", '\u00BD');
105 entities.Add ("frac34", '\u00BE');
106 entities.Add ("iquest", '\u00BF');
107 entities.Add ("Agrave", '\u00C0');
108 entities.Add ("Aacute", '\u00C1');
109 entities.Add ("Acirc", '\u00C2');
110 entities.Add ("Atilde", '\u00C3');
111 entities.Add ("Auml", '\u00C4');
112 entities.Add ("Aring", '\u00C5');
113 entities.Add ("AElig", '\u00C6');
114 entities.Add ("Ccedil", '\u00C7');
115 entities.Add ("Egrave", '\u00C8');
116 entities.Add ("Eacute", '\u00C9');
117 entities.Add ("Ecirc", '\u00CA');
118 entities.Add ("Euml", '\u00CB');
119 entities.Add ("Igrave", '\u00CC');
120 entities.Add ("Iacute", '\u00CD');
121 entities.Add ("Icirc", '\u00CE');
122 entities.Add ("Iuml", '\u00CF');
123 entities.Add ("ETH", '\u00D0');
124 entities.Add ("Ntilde", '\u00D1');
125 entities.Add ("Ograve", '\u00D2');
126 entities.Add ("Oacute", '\u00D3');
127 entities.Add ("Ocirc", '\u00D4');
128 entities.Add ("Otilde", '\u00D5');
129 entities.Add ("Ouml", '\u00D6');
130 entities.Add ("times", '\u00D7');
131 entities.Add ("Oslash", '\u00D8');
132 entities.Add ("Ugrave", '\u00D9');
133 entities.Add ("Uacute", '\u00DA');
134 entities.Add ("Ucirc", '\u00DB');
135 entities.Add ("Uuml", '\u00DC');
136 entities.Add ("Yacute", '\u00DD');
137 entities.Add ("THORN", '\u00DE');
138 entities.Add ("szlig", '\u00DF');
139 entities.Add ("agrave", '\u00E0');
140 entities.Add ("aacute", '\u00E1');
141 entities.Add ("acirc", '\u00E2');
142 entities.Add ("atilde", '\u00E3');
143 entities.Add ("auml", '\u00E4');
144 entities.Add ("aring", '\u00E5');
145 entities.Add ("aelig", '\u00E6');
146 entities.Add ("ccedil", '\u00E7');
147 entities.Add ("egrave", '\u00E8');
148 entities.Add ("eacute", '\u00E9');
149 entities.Add ("ecirc", '\u00EA');
150 entities.Add ("euml", '\u00EB');
151 entities.Add ("igrave", '\u00EC');
152 entities.Add ("iacute", '\u00ED');
153 entities.Add ("icirc", '\u00EE');
154 entities.Add ("iuml", '\u00EF');
155 entities.Add ("eth", '\u00F0');
156 entities.Add ("ntilde", '\u00F1');
157 entities.Add ("ograve", '\u00F2');
158 entities.Add ("oacute", '\u00F3');
159 entities.Add ("ocirc", '\u00F4');
160 entities.Add ("otilde", '\u00F5');
161 entities.Add ("ouml", '\u00F6');
162 entities.Add ("divide", '\u00F7');
163 entities.Add ("oslash", '\u00F8');
164 entities.Add ("ugrave", '\u00F9');
165 entities.Add ("uacute", '\u00FA');
166 entities.Add ("ucirc", '\u00FB');
167 entities.Add ("uuml", '\u00FC');
168 entities.Add ("yacute", '\u00FD');
169 entities.Add ("thorn", '\u00FE');
170 entities.Add ("yuml", '\u00FF');
171 entities.Add ("fnof", '\u0192');
172 entities.Add ("Alpha", '\u0391');
173 entities.Add ("Beta", '\u0392');
174 entities.Add ("Gamma", '\u0393');
175 entities.Add ("Delta", '\u0394');
176 entities.Add ("Epsilon", '\u0395');
177 entities.Add ("Zeta", '\u0396');
178 entities.Add ("Eta", '\u0397');
179 entities.Add ("Theta", '\u0398');
180 entities.Add ("Iota", '\u0399');
181 entities.Add ("Kappa", '\u039A');
182 entities.Add ("Lambda", '\u039B');
183 entities.Add ("Mu", '\u039C');
184 entities.Add ("Nu", '\u039D');
185 entities.Add ("Xi", '\u039E');
186 entities.Add ("Omicron", '\u039F');
187 entities.Add ("Pi", '\u03A0');
188 entities.Add ("Rho", '\u03A1');
189 entities.Add ("Sigma", '\u03A3');
190 entities.Add ("Tau", '\u03A4');
191 entities.Add ("Upsilon", '\u03A5');
192 entities.Add ("Phi", '\u03A6');
193 entities.Add ("Chi", '\u03A7');
194 entities.Add ("Psi", '\u03A8');
195 entities.Add ("Omega", '\u03A9');
196 entities.Add ("alpha", '\u03B1');
197 entities.Add ("beta", '\u03B2');
198 entities.Add ("gamma", '\u03B3');
199 entities.Add ("delta", '\u03B4');
200 entities.Add ("epsilon", '\u03B5');
201 entities.Add ("zeta", '\u03B6');
202 entities.Add ("eta", '\u03B7');
203 entities.Add ("theta", '\u03B8');
204 entities.Add ("iota", '\u03B9');
205 entities.Add ("kappa", '\u03BA');
206 entities.Add ("lambda", '\u03BB');
207 entities.Add ("mu", '\u03BC');
208 entities.Add ("nu", '\u03BD');
209 entities.Add ("xi", '\u03BE');
210 entities.Add ("omicron", '\u03BF');
211 entities.Add ("pi", '\u03C0');
212 entities.Add ("rho", '\u03C1');
213 entities.Add ("sigmaf", '\u03C2');
214 entities.Add ("sigma", '\u03C3');
215 entities.Add ("tau", '\u03C4');
216 entities.Add ("upsilon", '\u03C5');
217 entities.Add ("phi", '\u03C6');
218 entities.Add ("chi", '\u03C7');
219 entities.Add ("psi", '\u03C8');
220 entities.Add ("omega", '\u03C9');
221 entities.Add ("thetasym", '\u03D1');
222 entities.Add ("upsih", '\u03D2');
223 entities.Add ("piv", '\u03D6');
224 entities.Add ("bull", '\u2022');
225 entities.Add ("hellip", '\u2026');
226 entities.Add ("prime", '\u2032');
227 entities.Add ("Prime", '\u2033');
228 entities.Add ("oline", '\u203E');
229 entities.Add ("frasl", '\u2044');
230 entities.Add ("weierp", '\u2118');
231 entities.Add ("image", '\u2111');
232 entities.Add ("real", '\u211C');
233 entities.Add ("trade", '\u2122');
234 entities.Add ("alefsym", '\u2135');
235 entities.Add ("larr", '\u2190');
236 entities.Add ("uarr", '\u2191');
237 entities.Add ("rarr", '\u2192');
238 entities.Add ("darr", '\u2193');
239 entities.Add ("harr", '\u2194');
240 entities.Add ("crarr", '\u21B5');
241 entities.Add ("lArr", '\u21D0');
242 entities.Add ("uArr", '\u21D1');
243 entities.Add ("rArr", '\u21D2');
244 entities.Add ("dArr", '\u21D3');
245 entities.Add ("hArr", '\u21D4');
246 entities.Add ("forall", '\u2200');
247 entities.Add ("part", '\u2202');
248 entities.Add ("exist", '\u2203');
249 entities.Add ("empty", '\u2205');
250 entities.Add ("nabla", '\u2207');
251 entities.Add ("isin", '\u2208');
252 entities.Add ("notin", '\u2209');
253 entities.Add ("ni", '\u220B');
254 entities.Add ("prod", '\u220F');
255 entities.Add ("sum", '\u2211');
256 entities.Add ("minus", '\u2212');
257 entities.Add ("lowast", '\u2217');
258 entities.Add ("radic", '\u221A');
259 entities.Add ("prop", '\u221D');
260 entities.Add ("infin", '\u221E');
261 entities.Add ("ang", '\u2220');
262 entities.Add ("and", '\u2227');
263 entities.Add ("or", '\u2228');
264 entities.Add ("cap", '\u2229');
265 entities.Add ("cup", '\u222A');
266 entities.Add ("int", '\u222B');
267 entities.Add ("there4", '\u2234');
268 entities.Add ("sim", '\u223C');
269 entities.Add ("cong", '\u2245');
270 entities.Add ("asymp", '\u2248');
271 entities.Add ("ne", '\u2260');
272 entities.Add ("equiv", '\u2261');
273 entities.Add ("le", '\u2264');
274 entities.Add ("ge", '\u2265');
275 entities.Add ("sub", '\u2282');
276 entities.Add ("sup", '\u2283');
277 entities.Add ("nsub", '\u2284');
278 entities.Add ("sube", '\u2286');
279 entities.Add ("supe", '\u2287');
280 entities.Add ("oplus", '\u2295');
281 entities.Add ("otimes", '\u2297');
282 entities.Add ("perp", '\u22A5');
283 entities.Add ("sdot", '\u22C5');
284 entities.Add ("lceil", '\u2308');
285 entities.Add ("rceil", '\u2309');
286 entities.Add ("lfloor", '\u230A');
287 entities.Add ("rfloor", '\u230B');
288 entities.Add ("lang", '\u2329');
289 entities.Add ("rang", '\u232A');
290 entities.Add ("loz", '\u25CA');
291 entities.Add ("spades", '\u2660');
292 entities.Add ("clubs", '\u2663');
293 entities.Add ("hearts", '\u2665');
294 entities.Add ("diams", '\u2666');
295 entities.Add ("quot", '\u0022');
296 entities.Add ("amp", '\u0026');
297 entities.Add ("lt", '\u003C');
298 entities.Add ("gt", '\u003E');
299 entities.Add ("OElig", '\u0152');
300 entities.Add ("oelig", '\u0153');
301 entities.Add ("Scaron", '\u0160');
302 entities.Add ("scaron", '\u0161');
303 entities.Add ("Yuml", '\u0178');
304 entities.Add ("circ", '\u02C6');
305 entities.Add ("tilde", '\u02DC');
306 entities.Add ("ensp", '\u2002');
307 entities.Add ("emsp", '\u2003');
308 entities.Add ("thinsp", '\u2009');
309 entities.Add ("zwnj", '\u200C');
310 entities.Add ("zwj", '\u200D');
311 entities.Add ("lrm", '\u200E');
312 entities.Add ("rlm", '\u200F');
313 entities.Add ("ndash", '\u2013');
314 entities.Add ("mdash", '\u2014');
315 entities.Add ("lsquo", '\u2018');
316 entities.Add ("rsquo", '\u2019');
317 entities.Add ("sbquo", '\u201A');
318 entities.Add ("ldquo", '\u201C');
319 entities.Add ("rdquo", '\u201D');
320 entities.Add ("bdquo", '\u201E');
321 entities.Add ("dagger", '\u2020');
322 entities.Add ("Dagger", '\u2021');
323 entities.Add ("permil", '\u2030');
324 entities.Add ("lsaquo", '\u2039');
325 entities.Add ("rsaquo", '\u203A');
326 entities.Add ("euro", '\u20AC');
329 public HttpUtility ()
333 #endregion // Constructors
337 public static void HtmlAttributeEncode (string s, TextWriter output)
339 output.Write(HtmlAttributeEncode(s));
342 public static string HtmlAttributeEncode (string s)
347 if (s.IndexOf ('&') == -1 && s.IndexOf ('"') == -1 && s.IndexOf ('<') == -1)
350 StringBuilder output = new StringBuilder ();
351 foreach (char c in s)
354 output.Append ("&");
357 output.Append (""");
360 output.Append ("<");
367 return output.ToString();
370 public static string UrlDecode (string str)
372 return UrlDecode(str, Encoding.UTF8);
375 private static char [] GetChars (MemoryStream b, Encoding e)
377 return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
380 public static string UrlDecode (string s, Encoding e)
385 if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
391 StringBuilder output = new StringBuilder ();
393 MemoryStream bytes = new MemoryStream ();
396 for (int i = 0; i < len; i++) {
397 if (s [i] == '%' && i + 2 < len && s [i + 1] != '%') {
398 if (s [i + 1] == 'u' && i + 5 < len) {
399 if (bytes.Length > 0) {
400 output.Append (GetChars (bytes, e));
404 xchar = GetChar (s, i + 2, 4);
406 output.Append ((char) xchar);
411 } else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
412 bytes.WriteByte ((byte) xchar);
420 if (bytes.Length > 0) {
421 output.Append (GetChars (bytes, e));
428 output.Append (s [i]);
432 if (bytes.Length > 0) {
433 output.Append (GetChars (bytes, e));
437 return output.ToString ();
440 public static string UrlDecode (byte [] bytes, Encoding e)
445 return UrlDecode (bytes, 0, bytes.Length, e);
448 private static int GetInt (byte b)
451 if (c >= '0' && c <= '9')
454 if (c >= 'a' && c <= 'f')
457 if (c >= 'A' && c <= 'F')
463 private static int GetChar (byte [] bytes, int offset, int length)
466 int end = length + offset;
467 for (int i = offset; i < end; i++) {
468 int current = GetInt (bytes [i]);
471 value = (value << 4) + current;
477 private static int GetChar (string str, int offset, int length)
480 int end = length + offset;
481 for (int i = offset; i < end; i++) {
486 int current = GetInt ((byte) c);
489 val = (val << 4) + current;
495 public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
503 throw new ArgumentNullException ("bytes");
505 if (offset < 0 || offset > bytes.Length)
506 throw new ArgumentOutOfRangeException ("offset");
508 if (count < 0 || offset + count > bytes.Length)
509 throw new ArgumentOutOfRangeException ("count");
511 StringBuilder output = new StringBuilder ();
512 MemoryStream acc = new MemoryStream ();
514 int end = count + offset;
516 for (int i = offset; i < end; i++) {
517 if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
518 if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
519 if (acc.Length > 0) {
520 output.Append (GetChars (acc, e));
523 xchar = GetChar (bytes, i + 2, 4);
525 output.Append ((char) xchar);
529 } else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
530 acc.WriteByte ((byte) xchar);
536 if (acc.Length > 0) {
537 output.Append (GetChars (acc, e));
541 if (bytes [i] == '+') {
544 output.Append ((char) bytes [i]);
548 if (acc.Length > 0) {
549 output.Append (GetChars (acc, e));
553 return output.ToString ();
556 public static byte [] UrlDecodeToBytes (byte [] bytes)
561 return UrlDecodeToBytes (bytes, 0, bytes.Length);
564 public static byte [] UrlDecodeToBytes (string str)
566 return UrlDecodeToBytes (str, Encoding.UTF8);
569 public static byte [] UrlDecodeToBytes (string str, Encoding e)
575 throw new ArgumentNullException ("e");
577 return UrlDecodeToBytes (e.GetBytes (str));
580 public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
587 int len = bytes.Length;
588 if (offset < 0 || offset >= len)
589 throw new ArgumentOutOfRangeException("offset");
591 if (count < 0 || offset > len - count)
592 throw new ArgumentOutOfRangeException("count");
594 MemoryStream result = new MemoryStream ();
595 int end = offset + count;
596 for (int i = offset; i < end; i++){
597 char c = (char) bytes [i];
600 } else if (c == '%' && i < end - 2) {
601 int xchar = GetChar (bytes, i + 1, 2);
607 result.WriteByte ((byte) c);
610 return result.ToArray ();
613 public static string UrlEncode(string str)
615 return UrlEncode(str, Encoding.UTF8);
618 public static string UrlEncode (string s, Encoding Enc)
626 byte [] bytes = Enc.GetBytes (s);
627 return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
630 public static string UrlEncode (byte [] bytes)
635 if (bytes.Length == 0)
638 return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
641 public static string UrlEncode (byte [] bytes, int offset, int count)
646 if (bytes.Length == 0)
649 return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, offset, count));
652 public static byte [] UrlEncodeToBytes (string str)
654 return UrlEncodeToBytes (str, Encoding.UTF8);
657 public static byte [] UrlEncodeToBytes (string str, Encoding e)
665 byte [] bytes = e.GetBytes (str);
666 return UrlEncodeToBytes (bytes, 0, bytes.Length);
669 public static byte [] UrlEncodeToBytes (byte [] bytes)
674 if (bytes.Length == 0)
677 return UrlEncodeToBytes (bytes, 0, bytes.Length);
680 static char [] hexChars = "0123456789abcdef".ToCharArray ();
681 const string notEncoded = "!'()*-._";
683 static void UrlEncodeChar (char c, Stream result, bool isUnicode) {
685 //FIXME: what happens when there is an internal error?
687 // throw new ArgumentOutOfRangeException ("c", c, "c must be less than 256");
691 result.WriteByte ((byte)'%');
692 result.WriteByte ((byte)'u');
694 result.WriteByte ((byte)hexChars [idx]);
695 idx = (i >> 8) & 0x0F;
696 result.WriteByte ((byte)hexChars [idx]);
697 idx = (i >> 4) & 0x0F;
698 result.WriteByte ((byte)hexChars [idx]);
700 result.WriteByte ((byte)hexChars [idx]);
704 if (c>' ' && notEncoded.IndexOf (c)!=-1) {
705 result.WriteByte ((byte)c);
709 result.WriteByte ((byte)'+');
713 (c < 'A' && c > '9') ||
714 (c > 'Z' && c < 'a') ||
716 if (isUnicode && c > 127) {
717 result.WriteByte ((byte)'%');
718 result.WriteByte ((byte)'u');
719 result.WriteByte ((byte)'0');
720 result.WriteByte ((byte)'0');
723 result.WriteByte ((byte)'%');
725 int idx = ((int) c) >> 4;
726 result.WriteByte ((byte)hexChars [idx]);
727 idx = ((int) c) & 0x0F;
728 result.WriteByte ((byte)hexChars [idx]);
731 result.WriteByte ((byte)c);
734 public static byte [] UrlEncodeToBytes (byte [] bytes, int offset, int count)
739 int len = bytes.Length;
743 if (offset < 0 || offset >= len)
744 throw new ArgumentOutOfRangeException("offset");
746 if (count < 0 || count > len - offset)
747 throw new ArgumentOutOfRangeException("count");
749 MemoryStream result = new MemoryStream (count);
750 int end = offset + count;
751 for (int i = offset; i < end; i++)
752 UrlEncodeChar ((char)bytes [i], result, false);
754 return result.ToArray();
757 public static string UrlEncodeUnicode (string str)
762 return Encoding.ASCII.GetString (UrlEncodeUnicodeToBytes (str));
765 public static byte [] UrlEncodeUnicodeToBytes (string str)
773 MemoryStream result = new MemoryStream (str.Length);
774 foreach (char c in str){
775 UrlEncodeChar (c, result, true);
777 return result.ToArray ();
781 /// Decodes an HTML-encoded string and returns the decoded string.
783 /// <param name="s">The HTML string to decode. </param>
784 /// <returns>The decoded text.</returns>
785 public static string HtmlDecode (string s)
788 throw new ArgumentNullException ("s");
790 if (s.IndexOf ('&') == -1)
793 StringBuilder entity = new StringBuilder ();
794 StringBuilder output = new StringBuilder ();
797 // 1 -> right after '&'
798 // 2 -> between '&' and ';' but no '#'
799 // 3 -> '#' found after '&' and getting numbers
802 bool have_trailing_digits = false;
804 for (int i = 0; i < len; i++) {
818 if (have_trailing_digits) {
819 entity.Append (number.ToString (CultureInfo.InvariantCulture));
820 have_trailing_digits = false;
823 output.Append (entity.ToString ());
832 output.Append (entity.ToString ());
844 } else if (state == 2) {
847 string key = entity.ToString ();
848 if (key.Length > 1 && Entities.ContainsKey (key.Substring (1, key.Length - 2)))
849 key = Entities [key.Substring (1, key.Length - 2)].ToString ();
855 } else if (state == 3) {
857 if (number > 65535) {
858 output.Append ("&#");
859 output.Append (number.ToString (CultureInfo.InvariantCulture));
862 output.Append ((char) number);
866 have_trailing_digits = false;
867 } else if (Char.IsDigit (c)) {
868 number = number * 10 + ((int) c - '0');
869 have_trailing_digits = true;
872 if (have_trailing_digits) {
873 entity.Append (number.ToString (CultureInfo.InvariantCulture));
874 have_trailing_digits = false;
881 if (entity.Length > 0) {
882 output.Append (entity.ToString ());
883 } else if (have_trailing_digits) {
884 output.Append (number.ToString (CultureInfo.InvariantCulture));
886 return output.ToString ();
890 /// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.
892 /// <param name="s">The HTML string to decode</param>
893 /// <param name="output">The TextWriter output stream containing the decoded string. </param>
894 public static void HtmlDecode(string s, TextWriter output)
897 output.Write (HtmlDecode (s));
901 /// HTML-encodes a string and returns the encoded string.
903 /// <param name="s">The text string to encode. </param>
904 /// <returns>The HTML-encoded text.</returns>
905 public static string HtmlEncode (string s)
910 StringBuilder output = new StringBuilder ();
912 foreach (char c in s)
915 output.Append ("&");
918 output.Append (">");
921 output.Append ("<");
924 output.Append (""");
927 // MS starts encoding with &# from 160 and stops at 255.
928 // We don't do that. One reason is the 65308/65310 unicode
929 // characters that look like '<' and '>'.
931 output.Append ("&#");
932 output.Append (((int) c).ToString (CultureInfo.InvariantCulture));
939 return output.ToString ();
943 /// HTML-encodes a string and sends the resulting output to a TextWriter output stream.
945 /// <param name="s">The string to encode. </param>
946 /// <param name="output">The TextWriter output stream containing the encoded string. </param>
947 public static void HtmlEncode(string s, TextWriter output)
950 output.Write (HtmlEncode (s));
954 public static string UrlPathEncode (string s)
956 if (s == null || s.Length == 0)
959 MemoryStream result = new MemoryStream ();
960 int length = s.Length;
961 for (int i = 0; i < length; i++) {
962 UrlPathEncodeChar (s [i], result);
964 return Encoding.ASCII.GetString (result.ToArray ());
967 static void UrlPathEncodeChar (char c, Stream result) {
969 byte [] bIn = Encoding.UTF8.GetBytes (c.ToString ());
970 for (int i = 0; i < bIn.Length; i++) {
971 result.WriteByte ((byte) '%');
972 int idx = ((int) bIn [i]) >> 4;
973 result.WriteByte ((byte) hexChars [idx]);
974 idx = ((int) bIn [i]) & 0x0F;
975 result.WriteByte ((byte) hexChars [idx]);
979 result.WriteByte ((byte) '%');
980 result.WriteByte ((byte) '2');
981 result.WriteByte ((byte) '0');
984 result.WriteByte ((byte) c);
989 public static NameValueCollection ParseQueryString (string query)
991 return ParseQueryString (query, Encoding.UTF8);
994 public static NameValueCollection ParseQueryString (string query, Encoding encoding)
997 throw new ArgumentNullException ("query");
998 if (encoding == null)
999 throw new ArgumentNullException ("encoding");
1000 if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))
1001 return new NameValueCollection ();
1002 if (query[0] == '?')
1003 query = query.Substring (1);
1005 NameValueCollection result = new NameValueCollection ();
1006 ParseQueryString (query, encoding, result);
1011 internal static void ParseQueryString (string query, Encoding encoding, NameValueCollection result)
1013 if (query.Length == 0)
1017 while (namePos <= query.Length) {
1018 int valuePos = -1, valueEnd = -1;
1019 for (int q = namePos; q < query.Length; q++) {
1020 if (valuePos == -1 && query[q] == '=') {
1022 } else if (query[q] == ';' || query[q] == '&') {
1029 if (valuePos == -1) {
1033 name = UrlDecode (query.Substring (namePos, valuePos - namePos - 1), encoding);
1037 valueEnd = query.Length;
1039 namePos = valueEnd + 1;
1041 value = UrlDecode (query.Substring (valuePos, valueEnd - valuePos), encoding);
1043 result.Add (name, value);
1044 if (namePos == -1) break;
1047 #endregion // Methods