Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smailliwcs/4f60fe4687aa967519aedd4f50dfdd8d to your computer and use it in GitHub Desktop.
Save smailliwcs/4f60fe4687aa967519aedd4f50dfdd8d to your computer and use it in GitHub Desktop.
Base64 serialization
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public static class Base64Extensions
{
private static IFormatter GetFormatter()
{
return new BinaryFormatter();
}
public static string ToBase64String(object value)
{
byte[] data;
if (value == null)
{
data = new byte[] { };
}
else
{
using (MemoryStream stream = new MemoryStream())
{
GetFormatter().Serialize(stream, value);
data = stream.ToArray();
}
}
return Convert.ToBase64String(data);
}
public static object FromBase64String(string value)
{
byte[] data = Convert.FromBase64String(value);
if (data.Length == 0)
{
return null;
}
else
{
using (MemoryStream stream = new MemoryStream(data))
{
return GetFormatter().Deserialize(stream);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment