Our first example demonstrates base64 encoding and decoding. Visual Basic .NET provides built-in support for base64 encoding/decoding.
This code demonstrates base64 encoding and decoding in Visual Basic .NET. Here’s what it does:
We start by importing the necessary namespaces.
We define a string that we’ll encode and decode.
We use Convert.ToBase64String to encode the string to standard base64. The string is first converted to a byte array using UTF-8 encoding.
For decoding, we use Convert.FromBase64String. This may throw an exception if the input is not valid base64, so we wrap it in a try-catch block.
Visual Basic .NET doesn’t have a built-in URL-safe base64 encoding, but we can create one by replacing + with -, / with _, and removing the trailing = padding characters.
To decode the URL-safe string, we need to reverse these changes: add back the padding and replace the characters back to their original forms before decoding.
To run this program, save it as Base64EncodingExample.vb and compile it using the Visual Basic compiler:
The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing + vs -), but they both decode to the original string as desired.