ToBase64String Example
This page was last reviewed on Nov 29, 2023.
Dot Net Perls
ToBase64String. Sometimes it is helpful to have a text string representation of a binary file like an image. This text could be stored in a database, or directly on a web page.
With the Convert class, we have many helpful conversion utility methods. And ToBase64String helps us convert a byte array into a string with base-64 encoding.
Byte Array
To begin, we include the System.IO namespace—this is for the File.ReadAllBytes function. The Convert class is part of the System namespace, which is part of every VB.NET program.
Step 1 We specify the path of a binary file—in this program, we are using an image. Then we read in the file with File.ReadAllBytes.
Step 2 We invoke the ToBase64String function, which receives a byte array and returns a String.
Imports System.IO Module Module1 Sub Main() ' Step 1: specify the path of the image, and read all bytes from it. Dim image = "programs/adobe.png" Dim data = File.ReadAllBytes(image) ' Step 2: Call Convert.ToBase64String function. Dim result = Convert.ToBase64String(data) Console.WriteLine(result) End Sub End Module
iVBORw0KGgoAAA ... AABJRU5ErkJggg==
Data URIs. On web pages (HTML documents) we can specify data URIs in the place of external HTTPS links. And the data returned by ToBase64String works inside these data URIs.
Summary. With .NET, we have many powerful features built into our languages, including base-64 encoding. There is no need in VB.NET to use an external library to encode images into text strings.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 29, 2023 (new).
© 2007-2024 Sam Allen.