|
|
Title | Make a String extension method to URL encode and decode strings in Visual Basic 2008 |
Description | This example shows how to make a String extension method to URL encode and decode strings in Visual Basic 2008. |
Keywords | string, extension method, URL encode, URL decode, Visual Basic 2008 |
Categories | Software Engineering, Strings, Internet |
|
|
The following exnetsion method adds a UrlEncode method to the String class. It loops through the string's characters. If a character is printable, the code adds it to the result string. If the character is a space, the code adds either a + or %20 to the result string. Finally, for other characters the code adds the character's hex value to the result string.
|
|
<Extension()> _
Public Function UrlEncode(ByVal s As String, Optional ByVal _
use_plus_for_space As Boolean = True) As String
Dim result As String = ""
For Each ch As String In s
Select Case Asc(ch)
Case 48 To 57, 65 To 90, 97 To 122
result &= ch
Case 32
If use_plus_for_space Then
result &= "+"
Else
result &= "%20"
End If
Case Else
result &= "%" & Hex(Asc(ch)).PadLeft(2, _
"0"c)
End Select
Next ch
Return result
End Function
|
|
The following extension method adds a UrlDecode function to the String class. It loops through the string looking for + signs and hex values, and converts them into their proper characters.
|
|
<Extension()> _
Public Function UrlDecode(ByVal s As String, Optional ByVal _
use_plus_for_space As Boolean = True) As String
Dim result As String = ""
Dim i As Integer = 0
Do While i < s.Length
Dim ch As String = s.Substring(i, 1)
Select Case ch
Case "+"
If use_plus_for_space Then
result &= "+"
Else
result &= " "
End If
i += 1
Case "%"
Dim num As Integer = _
Val("&H" & s.Substring(i + 1, 2))
result &= Chr(num)
i += 3
Case Else
result &= ch
i += 1
End Select
Loop
Return result
End Function
|
|
|
|
|
|