C# Convert Image File to Base64 String with Examples

  By : Suresh Dasari
  Posted On : 23-Apr-2023

Here we will learn what is base64 format and how to convert image or file to base64 string with examples.

What is Base64 Encoding?

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.

Convert Image File 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 System namespace.

 

By using 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 System.IO namespace.

 

Following is the example of converting a file to a base64 string in c#.

 

using System;
using System.IO;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         string fpath = @"D:\Test.PNG";

         byte[] bytes = File.ReadAllBytes(fpath);
         string file = Convert.ToBase64String(bytes);

         Console.WriteLine("Base64 String: " + file);
         Console.WriteLine("Press Enter Key to Exit..");
         Console.ReadLine();
      }
   }
}

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).

 

The 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.

 

C# Convert Image File to Base64 String Example Result

 

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#.