2007-05-16 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / class / System.Web / System.Web / HttpUtility.cs
1 // 
2 // System.Web.HttpUtility
3 //
4 // Authors:
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)
9 //
10 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
11 //
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:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
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.
30 //
31
32 using System.Collections;
33 using System.Collections.Specialized;
34 using System.Globalization;
35 using System.IO;
36 using System.Security.Permissions;
37 using System.Text;
38 using System.Web.Util;
39
40 namespace System.Web {
41
42         // CAS - no InheritanceDemand here as the class is sealed
43         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
44         public sealed class HttpUtility {
45 #if NET_2_0
46                 internal const char QueryParamSeparator = ';';
47 #else
48                 internal const char QueryParamSeparator = '&';
49 #endif
50                 #region Fields
51         
52                 static Hashtable entities;
53                 static object lock_ = new object ();
54         
55                 #endregion // Fields
56         
57                 static Hashtable Entities {
58                         get {
59                                 lock (lock_) {
60                                         if (entities == null)
61                                                 InitEntities ();
62
63                                         return entities;
64                                 }
65                         }
66                 }
67                 
68                 #region Constructors
69
70                 static void InitEntities ()
71                 {
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');
327                 }
328
329                 public HttpUtility () 
330                 {
331                 }
332         
333                 #endregion // Constructors
334         
335                 #region Methods
336         
337                 public static void HtmlAttributeEncode (string s, TextWriter output) 
338                 {
339                         output.Write(HtmlAttributeEncode(s));
340                 }
341         
342                 public static string HtmlAttributeEncode (string s) 
343                 {
344                         if (null == s) 
345                                 return null;
346         
347                         if (s.IndexOf ('&') == -1 && s.IndexOf ('"') == -1 && s.IndexOf ('<') == -1)
348                                 return s;
349
350                         StringBuilder output = new StringBuilder ();
351                         foreach (char c in s) 
352                                 switch (c) {
353                                 case '&' : 
354                                         output.Append ("&amp;");
355                                         break;
356                                 case '"' :
357                                         output.Append ("&quot;");
358                                         break;
359                                 case '<':
360                                         output.Append ("&lt;");
361                                         break;
362                                 default:
363                                         output.Append (c);
364                                         break;
365                                 }
366         
367                         return output.ToString();
368                 }
369         
370                 public static string UrlDecode (string str) 
371                 {
372                         return UrlDecode(str, Encoding.UTF8);
373                 }
374         
375                 private static char [] GetChars (MemoryStream b, Encoding e)
376                 {
377                         return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
378                 }
379
380                 public static string UrlDecode (string s, Encoding e)
381                 {
382                         if (null == s) 
383                                 return null;
384
385                         if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
386                                 return s;
387
388                         if (e == null)
389                                 e = Encoding.UTF8;
390         
391                         StringBuilder output = new StringBuilder ();
392                         long len = s.Length;
393                         MemoryStream bytes = new MemoryStream ();
394                         int xchar;
395         
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));
401                                                         bytes.SetLength (0);
402                                                 }
403
404                                                 xchar = GetChar (s, i + 2, 4);
405                                                 if (xchar != -1) {
406                                                         output.Append ((char) xchar);
407                                                         i += 5;
408                                                 } else {
409                                                         output.Append ('%');
410                                                 }
411                                         } else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
412                                                 bytes.WriteByte ((byte) xchar);
413                                                 i += 2;
414                                         } else {
415                                                 output.Append ('%');
416                                         }
417                                         continue;
418                                 }
419
420                                 if (bytes.Length > 0) {
421                                         output.Append (GetChars (bytes, e));
422                                         bytes.SetLength (0);
423                                 }
424
425                                 if (s [i] == '+') {
426                                         output.Append (' ');
427                                 } else {
428                                         output.Append (s [i]);
429                                 }
430                         }
431         
432                         if (bytes.Length > 0) {
433                                 output.Append (GetChars (bytes, e));
434                         }
435
436                         bytes = null;
437                         return output.ToString ();
438                 }
439         
440                 public static string UrlDecode (byte [] bytes, Encoding e)
441                 {
442                         if (bytes == null)
443                                 return null;
444
445                         return UrlDecode (bytes, 0, bytes.Length, e);
446                 }
447
448                 private static int GetInt (byte b)
449                 {
450                         char c = (char) b;
451                         if (c >= '0' && c <= '9')
452                                 return c - '0';
453
454                         if (c >= 'a' && c <= 'f')
455                                 return c - 'a' + 10;
456
457                         if (c >= 'A' && c <= 'F')
458                                 return c - 'A' + 10;
459
460                         return -1;
461                 }
462
463                 private static int GetChar (byte [] bytes, int offset, int length)
464                 {
465                         int value = 0;
466                         int end = length + offset;
467                         for (int i = offset; i < end; i++) {
468                                 int current = GetInt (bytes [i]);
469                                 if (current == -1)
470                                         return -1;
471                                 value = (value << 4) + current;
472                         }
473
474                         return value;
475                 }
476
477                 private static int GetChar (string str, int offset, int length)
478                 {
479                         int val = 0;
480                         int end = length + offset;
481                         for (int i = offset; i < end; i++) {
482                                 char c = str [i];
483                                 if (c > 127)
484                                         return -1;
485
486                                 int current = GetInt ((byte) c);
487                                 if (current == -1)
488                                         return -1;
489                                 val = (val << 4) + current;
490                         }
491
492                         return val;
493                 }
494                 
495                 public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
496                 {
497                         if (bytes == null)
498                                 return null;
499                         if (count == 0)
500                                 return String.Empty;
501
502                         if (bytes == null)
503                                 throw new ArgumentNullException ("bytes");
504
505                         if (offset < 0 || offset > bytes.Length)
506                                 throw new ArgumentOutOfRangeException ("offset");
507
508                         if (count < 0 || offset + count > bytes.Length)
509                                 throw new ArgumentOutOfRangeException ("count");
510
511                         StringBuilder output = new StringBuilder ();
512                         MemoryStream acc = new MemoryStream ();
513
514                         int end = count + offset;
515                         int xchar;
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));
521                                                         acc.SetLength (0);
522                                                 }
523                                                 xchar = GetChar (bytes, i + 2, 4);
524                                                 if (xchar != -1) {
525                                                         output.Append ((char) xchar);
526                                                         i += 5;
527                                                         continue;
528                                                 }
529                                         } else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
530                                                 acc.WriteByte ((byte) xchar);
531                                                 i += 2;
532                                                 continue;
533                                         }
534                                 }
535
536                                 if (acc.Length > 0) {
537                                         output.Append (GetChars (acc, e));
538                                         acc.SetLength (0);
539                                 }
540
541                                 if (bytes [i] == '+') {
542                                         output.Append (' ');
543                                 } else {
544                                         output.Append ((char) bytes [i]);
545                                 }
546                         }
547
548                         if (acc.Length > 0) {
549                                 output.Append (GetChars (acc, e));
550                         }
551                         
552                         acc = null;
553                         return output.ToString ();
554                 }
555         
556                 public static byte [] UrlDecodeToBytes (byte [] bytes)
557                 {
558                         if (bytes == null)
559                                 return null;
560
561                         return UrlDecodeToBytes (bytes, 0, bytes.Length);
562                 }
563
564                 public static byte [] UrlDecodeToBytes (string str)
565                 {
566                         return UrlDecodeToBytes (str, Encoding.UTF8);
567                 }
568
569                 public static byte [] UrlDecodeToBytes (string str, Encoding e)
570                 {
571                         if (str == null)
572                                 return null;
573
574                         if (e == null)
575                                 throw new ArgumentNullException ("e");
576
577                         return UrlDecodeToBytes (e.GetBytes (str));
578                 }
579
580                 public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
581                 {
582                         if (bytes == null)
583                                 return null;
584                         if (count == 0)
585                                 return new byte [0];
586
587                         int len = bytes.Length;
588                         if (offset < 0 || offset >= len)
589                                 throw new ArgumentOutOfRangeException("offset");
590
591                         if (count < 0 || offset > len - count)
592                                 throw new ArgumentOutOfRangeException("count");
593
594                         MemoryStream result = new MemoryStream ();
595                         int end = offset + count;
596                         for (int i = offset; i < end; i++){
597                                 char c = (char) bytes [i];
598                                 if (c == '+') {
599                                         c = ' ';
600                                 } else if (c == '%' && i < end - 2) {
601                                         int xchar = GetChar (bytes, i + 1, 2);
602                                         if (xchar != -1) {
603                                                 c = (char) xchar;
604                                                 i += 2;
605                                         }
606                                 }
607                                 result.WriteByte ((byte) c);
608                         }
609
610                         return result.ToArray ();
611                 }
612
613                 public static string UrlEncode(string str) 
614                 {
615                         return UrlEncode(str, Encoding.UTF8);
616                 }
617         
618                 public static string UrlEncode (string s, Encoding Enc) 
619                 {
620                         if (s == null)
621                                 return null;
622
623                         if (s == "")
624                                 return "";
625
626                         byte [] bytes = Enc.GetBytes (s);
627                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
628                 }
629           
630                 public static string UrlEncode (byte [] bytes)
631                 {
632                         if (bytes == null)
633                                 return null;
634
635                         if (bytes.Length == 0)
636                                 return "";
637
638                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
639                 }
640
641                 public static string UrlEncode (byte [] bytes, int offset, int count)
642                 {
643                         if (bytes == null)
644                                 return null;
645
646                         if (bytes.Length == 0)
647                                 return "";
648
649                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, offset, count));
650                 }
651
652                 public static byte [] UrlEncodeToBytes (string str)
653                 {
654                         return UrlEncodeToBytes (str, Encoding.UTF8);
655                 }
656
657                 public static byte [] UrlEncodeToBytes (string str, Encoding e)
658                 {
659                         if (str == null)
660                                 return null;
661
662                         if (str == "")
663                                 return new byte [0];
664
665                         byte [] bytes = e.GetBytes (str);
666                         return UrlEncodeToBytes (bytes, 0, bytes.Length);
667                 }
668
669                 public static byte [] UrlEncodeToBytes (byte [] bytes)
670                 {
671                         if (bytes == null)
672                                 return null;
673
674                         if (bytes.Length == 0)
675                                 return new byte [0];
676
677                         return UrlEncodeToBytes (bytes, 0, bytes.Length);
678                 }
679
680                 static char [] hexChars = "0123456789abcdef".ToCharArray ();
681                 const string notEncoded = "!'()*-._";
682
683                 static void UrlEncodeChar (char c, Stream result, bool isUnicode) {
684                         if (c > 255) {
685                                 //FIXME: what happens when there is an internal error?
686                                 //if (!isUnicode)
687                                 //      throw new ArgumentOutOfRangeException ("c", c, "c must be less than 256");
688                                 int idx;
689                                 int i = (int) c;
690
691                                 result.WriteByte ((byte)'%');
692                                 result.WriteByte ((byte)'u');
693                                 idx = i >> 12;
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]);
699                                 idx = i & 0x0F;
700                                 result.WriteByte ((byte)hexChars [idx]);
701                                 return;
702                         }
703                         
704                         if (c>' ' && notEncoded.IndexOf (c)!=-1) {
705                                 result.WriteByte ((byte)c);
706                                 return;
707                         }
708                         if (c==' ') {
709                                 result.WriteByte ((byte)'+');
710                                 return;
711                         }
712                         if (    (c < '0') ||
713                                 (c < 'A' && c > '9') ||
714                                 (c > 'Z' && c < 'a') ||
715                                 (c > 'z')) {
716                                 if (isUnicode && c > 127) {
717                                         result.WriteByte ((byte)'%');
718                                         result.WriteByte ((byte)'u');
719                                         result.WriteByte ((byte)'0');
720                                         result.WriteByte ((byte)'0');
721                                 }
722                                 else
723                                         result.WriteByte ((byte)'%');
724                                 
725                                 int idx = ((int) c) >> 4;
726                                 result.WriteByte ((byte)hexChars [idx]);
727                                 idx = ((int) c) & 0x0F;
728                                 result.WriteByte ((byte)hexChars [idx]);
729                         }
730                         else
731                                 result.WriteByte ((byte)c);
732                 }
733
734                 public static byte [] UrlEncodeToBytes (byte [] bytes, int offset, int count)
735                 {
736                         if (bytes == null)
737                                 return null;
738
739                         int len = bytes.Length;
740                         if (len == 0)
741                                 return new byte [0];
742
743                         if (offset < 0 || offset >= len)
744                                 throw new ArgumentOutOfRangeException("offset");
745
746                         if (count < 0 || count > len - offset)
747                                 throw new ArgumentOutOfRangeException("count");
748
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);
753
754                         return result.ToArray();
755                 }
756
757                 public static string UrlEncodeUnicode (string str)
758                 {
759                         if (str == null)
760                                 return null;
761
762                         return Encoding.ASCII.GetString (UrlEncodeUnicodeToBytes (str));
763                 }
764
765                 public static byte [] UrlEncodeUnicodeToBytes (string str)
766                 {
767                         if (str == null)
768                                 return null;
769
770                         if (str == "")
771                                 return new byte [0];
772
773                         MemoryStream result = new MemoryStream (str.Length);
774                         foreach (char c in str){
775                                 UrlEncodeChar (c, result, true);
776                         }
777                         return result.ToArray ();
778                 }
779
780                 /// <summary>
781                 /// Decodes an HTML-encoded string and returns the decoded string.
782                 /// </summary>
783                 /// <param name="s">The HTML string to decode. </param>
784                 /// <returns>The decoded text.</returns>
785                 public static string HtmlDecode (string s) 
786                 {
787                         if (s == null)
788                                 throw new ArgumentNullException ("s");
789
790                         if (s.IndexOf ('&') == -1)
791                                 return s;
792
793                         StringBuilder entity = new StringBuilder ();
794                         StringBuilder output = new StringBuilder ();
795                         int len = s.Length;
796                         // 0 -> nothing,
797                         // 1 -> right after '&'
798                         // 2 -> between '&' and ';' but no '#'
799                         // 3 -> '#' found after '&' and getting numbers
800                         int state = 0;
801                         int number = 0;
802                         bool have_trailing_digits = false;
803         
804                         for (int i = 0; i < len; i++) {
805                                 char c = s [i];
806                                 if (state == 0) {
807                                         if (c == '&') {
808                                                 entity.Append (c);
809                                                 state = 1;
810                                         } else {
811                                                 output.Append (c);
812                                         }
813                                         continue;
814                                 }
815
816                                 if (c == '&') {
817                                         state = 1;
818                                         if (have_trailing_digits) {
819                                                 entity.Append (number.ToString (CultureInfo.InvariantCulture));
820                                                 have_trailing_digits = false;
821                                         }
822
823                                         output.Append (entity.ToString ());
824                                         entity.Length = 0;
825                                         entity.Append ('&');
826                                         continue;
827                                 }
828
829                                 if (state == 1) {
830                                         if (c == ';') {
831                                                 state = 0;
832                                                 output.Append (entity.ToString ());
833                                                 output.Append (c);
834                                                 entity.Length = 0;
835                                         } else {
836                                                 number = 0;
837                                                 if (c != '#') {
838                                                         state = 2;
839                                                 } else {
840                                                         state = 3;
841                                                 }
842                                                 entity.Append (c);
843                                         }
844                                 } else if (state == 2) {
845                                         entity.Append (c);
846                                         if (c == ';') {
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 ();
850
851                                                 output.Append (key);
852                                                 state = 0;
853                                                 entity.Length = 0;
854                                         }
855                                 } else if (state == 3) {
856                                         if (c == ';') {
857                                                 if (number > 65535) {
858                                                         output.Append ("&#");
859                                                         output.Append (number.ToString (CultureInfo.InvariantCulture));
860                                                         output.Append (";");
861                                                 } else {
862                                                         output.Append ((char) number);
863                                                 }
864                                                 state = 0;
865                                                 entity.Length = 0;
866                                                 have_trailing_digits = false;
867                                         } else if (Char.IsDigit (c)) {
868                                                 number = number * 10 + ((int) c - '0');
869                                                 have_trailing_digits = true;
870                                         } else {
871                                                 state = 2;
872                                                 if (have_trailing_digits) {
873                                                         entity.Append (number.ToString (CultureInfo.InvariantCulture));
874                                                         have_trailing_digits = false;
875                                                 }
876                                                 entity.Append (c);
877                                         }
878                                 }
879                         }
880
881                         if (entity.Length > 0) {
882                                 output.Append (entity.ToString ());
883                         } else if (have_trailing_digits) {
884                                 output.Append (number.ToString (CultureInfo.InvariantCulture));
885                         }
886                         return output.ToString ();
887                 }
888         
889                 /// <summary>
890                 /// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.
891                 /// </summary>
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) 
895                 {
896                         if (s != null)
897                                 output.Write (HtmlDecode (s));
898                 }
899         
900                 /// <summary>
901                 /// HTML-encodes a string and returns the encoded string.
902                 /// </summary>
903                 /// <param name="s">The text string to encode. </param>
904                 /// <returns>The HTML-encoded text.</returns>
905                 public static string HtmlEncode (string s) 
906                 {
907                         if (s == null)
908                                 return null;
909
910                         StringBuilder output = new StringBuilder ();
911                         
912                         foreach (char c in s) 
913                                 switch (c) {
914                                 case '&' :
915                                         output.Append ("&amp;");
916                                         break;
917                                 case '>' : 
918                                         output.Append ("&gt;");
919                                         break;
920                                 case '<' :
921                                         output.Append ("&lt;");
922                                         break;
923                                 case '"' :
924                                         output.Append ("&quot;");
925                                         break;
926                                 default:
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 '>'.
930                                         if (c > 159) {
931                                                 output.Append ("&#");
932                                                 output.Append (((int) c).ToString (CultureInfo.InvariantCulture));
933                                                 output.Append (";");
934                                         } else {
935                                                 output.Append (c);
936                                         }
937                                         break;
938                                 }
939                         return output.ToString ();
940                 }
941         
942                 /// <summary>
943                 /// HTML-encodes a string and sends the resulting output to a TextWriter output stream.
944                 /// </summary>
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) 
948                 {
949                         if (s != null)
950                                 output.Write (HtmlEncode (s));
951                 }
952
953 #if NET_1_1
954                 public static string UrlPathEncode (string s)
955                 {
956                         if (s == null || s.Length == 0)
957                                 return s;
958
959                         MemoryStream result = new MemoryStream ();
960                         int length = s.Length;
961             for (int i = 0; i < length; i++) {
962                                 UrlPathEncodeChar (s [i], result);
963                         }
964                         return Encoding.ASCII.GetString (result.ToArray ());
965                 }
966                 
967                 static void UrlPathEncodeChar (char c, Stream result) {
968                         if (c > 127) {
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]);
976                                 }
977                         }
978                         else if (c == ' ') {
979                                 result.WriteByte ((byte) '%');
980                                 result.WriteByte ((byte) '2');
981                                 result.WriteByte ((byte) '0');
982                         }
983                         else
984                                 result.WriteByte ((byte) c);
985                 }
986 #endif
987
988 #if NET_2_0
989                 public static NameValueCollection ParseQueryString (string query)
990                 {
991                         return ParseQueryString (query, Encoding.UTF8);
992                 }
993
994                 public static NameValueCollection ParseQueryString (string query, Encoding encoding)
995                 {
996                         if (query == null)
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);
1004                                 
1005                         NameValueCollection result = new NameValueCollection ();
1006                         ParseQueryString (query, encoding, result);
1007                         return result;
1008                 }                               
1009 #endif
1010
1011                 internal static void ParseQueryString (string query, Encoding encoding, NameValueCollection result)
1012                 {
1013                         if (query.Length == 0)
1014                                 return;
1015
1016                         int namePos = 0;
1017                         bool first = true;
1018                         while (namePos <= query.Length) {
1019                                 int valuePos = -1, valueEnd = -1;
1020                                 for (int q = namePos; q < query.Length; q++) {
1021                                         if (valuePos == -1 && query[q] == '=') {
1022                                                 valuePos = q + 1;
1023                                         } else if (query[q] == ';' || query[q] == '&') {
1024                                                 valueEnd = q;
1025                                                 break;
1026                                         }
1027                                 }
1028
1029                                 if (first) {
1030                                         first = false;
1031                                         if (query [namePos] == '?')
1032                                                 namePos++;
1033                                 }
1034                                 
1035                                 string name, value;
1036                                 if (valuePos == -1) {
1037                                         name = null;
1038                                         valuePos = namePos;
1039                                 } else {
1040                                         name = UrlDecode (query.Substring (namePos, valuePos - namePos - 1), encoding);
1041                                 }
1042                                 if (valueEnd < 0) {
1043                                         namePos = -1;
1044                                         valueEnd = query.Length;
1045                                 } else {
1046                                         namePos = valueEnd + 1;
1047                                 }
1048                                 value = UrlDecode (query.Substring (valuePos, valueEnd - valuePos), encoding);
1049
1050                                 result.Add (name, value);
1051                                 if (namePos == -1)
1052                                         break;
1053                         }
1054                 }
1055                 #endregion // Methods
1056         }
1057 }
1058