Recipe 5.43. Converting a String to and from Base64


You want to convert a string to or from Base64 format for predictable transfer across a network.


Sample code folder: Chapter 05\Base64

To convert a string to Base64, first use System.Text.Encoding methods to convert the string to a byte array and then use the Convert.ToBase64String() method to convert the byte array to a Base64 string.

To convert a Base64 string back to the original string, use Convert. FromBase64String() to convert the string to a byte array, and then use the appropriate System.Text.Encoding method to convert the byte array to a string.


The following code demonstrates these steps as it converts a sample string to Base64 and back again:

 Dim quote As String = "The important thing is not to " & _    "stop questioning. --Albert Einstein" Dim quoteBytes As Byte() = _    System.Text.Encoding.UTF8.GetBytes(quote) Dim quote64 As String = Convert.ToBase64String(quoteBytes) Dim byteSet As Byte() = Convert.FromBase64String(quote64) Dim result As String = _    System.Text.Encoding.UTF8.GetString(byteSet) MsgBox(quote & vbNewLine & quote64 & vbNewLine & result) 

UTF8 encoding is used because the sample string's characters all fall within the range of standard ASCII characters. For other character sets, it's best to use Unicode encoding, in which case you should change both occurrences of "UTF8" to "Unicode" in the code sample. The byte array and the Base64 string will each be twice as large when using Unicode, but this eliminates the possibility of any data loss during the conversions.

Figure 5-51 shows the results of the above conversions as displayed by the message box.

Figure 5-51. A sample string converted to Base64 and back again

See Also

Recipe 5.33 also shows how to convert string data into an alternative format that uses only printable characters.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: