Here we will learn what is base64 format and how to convert image or file to base64 string with examples.
Base64 encoding is a process to convert binary data to ASCII string format. The base64 encoding process is useful when we want to transfer images or files from one system to another. To learn more about Base64, refer C# Encode and Decode String to Base64.
In c#, to convert an image or file to a Base64 string, first, we need to convert the file to a byte array, and then encode the byte array to a Base64 string using
Convert.ToBase64String() method that is available with the
File.ReadAllBytes() method, we can convert a file to a byte array in c#. The ReadAllBytes() method will read the content of the file as an array of bytes and it is available with the
Following is the example of converting a file to a base64 string in c#.
If you observe the example, we defined the path of the file (fpath) that we want to convert to a Base64 string. The
File.ReadAllBytes() method will read the contents of the file and convert it into a byte array (bytes).
Convert.ToBase64String() method will encode the byte array (bytes) as a Base64 string and that will be stored in the file variable.
When we execute the above example, we will get the result as shown below.
This is how we can convert an image or file to a base64 string using the ToBase64String method and send it across systems, store it in a database, etc. based on our requirements.
If you want to convert the Base64 string to a file in c#, we need to decode the Base64 string and write the binary data to a file. To learn more about it, check out Convert Base64 String to File in C#.