Convert FileStream to base64 string in C#

In this post, I will show how to convert a file on disk and returns the base64 string representation.

Why Encoding?

We used encoding when you want to stored or transfer binary data over media that supports only textual data. There are a lot of encoding available but the most popular is base64 encoding/decoding

public static string ToBase64String(string fileName)
{
	using (FileStream reader = new FileStream(fileName, FileMode.Open))
	{
		byte[] buffer = new byte[reader.Length];
		reader.Read(buffer, 0, (int)reader.Length);
		return Convert.ToBase64String(buffer);
	}
}
public static void ToString(string fileName, string serializedFile)
{
	using (System.IO.FileStream reader = System.IO.File.Create(fileName))
	{
		byte[] buffer = Convert.FromBase64String(serializedFile);
		reader.Write(buffer, 0, buffer.Length);
	}
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post