convert dictionary or list to byte[]

BinaryFormatter is now a security risk. If I find a good way to do this without using it I'll be back

https://docs.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/5.0/binaryformatter-serialization-obsolete

Edit: This is still the top result in Google so I'll show what I've done to move away from BinaryFormatter

You need Newtonsoft.Json

public static class ExtendedSerializerExtensions
{
    private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.Auto,
    };

    public static byte[] Serialize<T>(this T source)
    {
        var asString = JsonConvert.SerializeObject(source, SerializerSettings);
        return Encoding.Unicode.GetBytes(asString);
    }

    public static T Deserialize<T>(this byte[] source)
    {
        var asString = Encoding.Unicode.GetString(source);
        return JsonConvert.DeserializeObject<T>(asString);
    }
}

It's not very far to go from here if you need a stream rather than a byte array


You may want to try serialization.

var binFormatter = new BinaryFormatter();
var mStream = new MemoryStream();
binFormatter.Serialize(mStream, myObjToSerialize);

//This gives you the byte array.
mStream.ToArray();

And then if you want to turn the byte array back into an object:

var mStream = new MemoryStream();
var binFormatter = new BinaryFormatter();

// Where 'objectBytes' is your byte array.
mStream.Write (objectBytes, 0, objectBytes.Length);
mStream.Position = 0;

var myObject = binFormatter.Deserialize(mStream) as YourObjectType;

Update:

Microsoft warns about using BinaryFormatter because it is "insecure and can't be made secure".

Please read aka.ms/binaryformatter for more details.

Preferred alternatives

.NET offers several in-box serializers that can handle untrusted data safely:

  • XmlSerializer and DataContractSerializer to serialize object graphs into and from XML. Do not confuse DataContractSerializer with NetDataContractSerializer.
  • BinaryReader and BinaryWriter for XML and JSON.
  • The System.Text.Json APIs to serialize object graphs into JSON.