cansik

Encode URL

Feb 10th, 2012
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.80 KB | None | 0 0
  1. /// <summary>
  2. /// Encodes an URL
  3. /// </summary>
  4. /// <param name="str">Input URL</param>
  5. /// <returns>Returns an encoded URL</returns>
  6. public static string Encode(string str)
  7. {
  8.     StringBuilder b = new StringBuilder();
  9.  
  10.     foreach (Char c in str)
  11.     {
  12.         int decValue = (int)c;
  13.  
  14.         //Exclude Unreserved Characters (RFC 3986)
  15.         if ((decValue >= 48 && decValue <= 57) || // 0 - 9
  16.             (decValue >= 65 && decValue <= 90) || // A - Z
  17.             (decValue >= 97 && decValue <= 122) || // a - z
  18.             decValue == 45 || // -
  19.             decValue == 95 || // _
  20.             decValue == 46 || // .
  21.             decValue == 126) // ~
  22.         {
  23.             b.Append(c);
  24.         }
  25.         else
  26.         {
  27.             b.Append("%" + decValue.ToString("X"));
  28.         }
  29.     }
  30.  
  31.     return b.ToString();
  32. }
Advertisement
Add Comment
Please, Sign In to add comment