URL Encoding
URL-encodes string. This algorithm is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
public static string EncodeURL(string data)
{
StringBuilder result = new StringBuilder(data.Length);
foreach (char c in data)
{
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9'))
{
result.Append(c);
}
else
{
result.Append('%');
result.Append(DecimalToHexadecimal(c).PadLeft(2, '0'));
}
}
return result.ToString();
}
private static string DecimalToHexadecimal(int dec)
{
if (dec < 1) return "0";
int hex = dec;
string hexStr = string.Empty;
while (dec > 0)
{
hex = dec % 16;
if (hex < 10)
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 48).ToString());
else
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 55).ToString());
dec /= 16;
}
return hexStr;
}
Example
string data = "jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^";
string value = EncodeURL(data);
Output
jdfgsdhfsdfsd%206445dsfsd7fg%2F%2A%2F%2Bbfjsdgf%25%24%5E