Serialize files to base64 strings

Feb 25, 2007

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);
 }
}

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (2) -

 Michael Thomas
Michael Thomas
2/26/2007 2:34:42 AM #

Something that would make this a little easier for Serialize method:
return Convert.ToMase64String(System.IO.File.ReadAllBytes(fileName));

Mads Kristensen
Mads Kristensen
2/26/2007 11:23:31 AM #

That's a nicer way to do it Michael. Thanks.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.