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 MemoryStream
instead of the file stream:
Stream s = new MemoryStream();
This will place the data in the s
variable, which you can read later on in your application.
In order to read from it, you will need to set the Position
to 0, so seeking will start from the beginning of the stream (if reading in chunks), or use ToArray()
on it to retrieve the complete content.
To put it bluntly: I would put them in another table in the database that has a one-to-many foreign-key relationship with its parent record.
That way, you can do normal DB operations with them, like retrieving parent records based on which ints are in the child table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With