Serialize files to base64 strings
Today, I needed to store images in XML files so I had to serialize an image file into text so it could be written in the XML file. Of course, it should also be deserialized back to an image again by reading from the XML file. The result is the following two methods.
The first method serializes a file on disk and returns the base64 string representation.
public static string Serialize(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);
}
}
The next deserializes a base64 string and writes it to the disk.
public static void DeSerialize(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);
}
}
Comments
Comments are closed