Friday, January 4, 2008

How To Serialize and Desrialize Files to Base64 Strings

In this post i will show how to serializes and deserialize  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);
        }
    }

No comments:

Post a Comment