Mega Code Archive

 
Categories / C# / Network
 

URL Encoding

using System; using System.Collections; public static class HTTPUtility {     #region URL Encoding     public static string UrlEncode(string s)     {         if (s == null)             return null;         string result = string.Empty;         for (int i = 0; i < s.Length; i++)         {             if (ShouldEncodeChar(s[i]))                 result += '%' + ByteToHex((byte)s[i]);             else                 result += s[i];         }         return result;     }     private static bool ShouldEncodeChar(char c)     {         // Safe characters defined by RFC3986:         // http://oauth.net/core/1.0/#encoding_parameters         if (c >= '0' && c <= '9')             return false;         if (c >= 'A' && c <= 'Z')             return false;         if (c >= 'a' && c <= 'z')             return false;         switch (c)         {             case '-':             case '.':             case '_':             case '~':                 return false;         }         // All other characters should be encoded         return true;     }     public static string ByteToHex(byte b)     {         const string hex = "0123456789ABCDEF";         int lowNibble = b & 0x0F;         int highNibble = (b & 0xF0) >> 4;         string s = new string(new char[] { hex[highNibble], hex[lowNibble] });         return s;     }     #endregion }