In C# how can I serialize a List<int> to a byte[] in order to store it in a DB field?
I know how to serialize to a file on the disk, but how do I just serialize to a variable?
Here is how I serialized to the disk:
List<int> l = IenumerableofInts.ToList();
Stream s = File.OpenWrite("file.bin");
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(s, lR);
s.Close();
I’m sure it’s much the same but I just can’t wrap my head around it.
Use a
MemoryStreaminstead of the file stream:This will place the data in the
svariable, which you can read later on in your application.In order to read from it, you will need to set the
Positionto 0, so seeking will start from the beginning of the stream (if reading in chunks), or useToArray()on it to retrieve the complete content.