Created
September 22, 2020 15:25
-
-
Save smailliwcs/4f60fe4687aa967519aedd4f50dfdd8d to your computer and use it in GitHub Desktop.
Base64 serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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