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 Shared Function EncodeURL(data As String) As String
	Dim result As New StringBuilder(data.Length)

	For Each c As Char In data
		If ("a"c <= c AndAlso c <= "z"c) OrElse ("A"c <= c AndAlso c <= "Z"c) OrElse ("0"c <= c AndAlso c <= "9"c) Then
			result.Append(c)
		Else
			result.Append("%"c)
			result.Append(DecimalToHexadecimal(AscW(c)).PadLeft(2, "0"c))
		End If
	Next

	Return result.ToString()
End Function

Private Shared Function DecimalToHexadecimal(dec As Integer) As String
	If dec < 1 Then Return "0"

	Dim hex As Integer = dec
	Dim hexStr As String = String.Empty

	While dec > 0
		hex = dec Mod 16

		If hex < 10 Then
			hexStr = hexStr.Insert(0, Convert.ToChar(hex + 48).ToString())
		Else
			hexStr = hexStr.Insert(0, Convert.ToChar(hex + 55).ToString())
		End If

		dec \= 16
	End While

	Return hexStr
End Function
								


Example

									Dim data = "jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^"
Dim value = EncodeURL(data)
								


Output

									jdfgsdhfsdfsd%206445dsfsd7fg%2F%2A%2F%2Bbfjsdgf%25%24%5E