'cast a stream or byte array to object
In our game, to save a "Ghost" (a serializable class which is record of how someone played a level), we use straightforward
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(filePath, FileMode.Open);
object ghost = bf.Deserialize(file);
file.Close();
return (Ghost)ghost;
Which works perfectly, and to save a Ghost,
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(filePath);
bf.Serialize(file, ghost);
file.Close();
Again, perfect.
Thing is, we're loading things from the web too (specifically Amazon S3), which, in the end, gives a generic stream.
What I want to do is save that stream to file,
using( BinaryReader reader = new BinaryReader(stream) )
{
FileStream file = File.Create(downloadPath);
byte[] array = ReadAllBytes(reader);
file.Write(array, 0, array.Length);
file.Close();
}
But also deliver those bytes back to the requesting code, to be able to cast them into the Ghost object. Currently, we save the ghost, tell the requesting code it's been saved, and they just read it from there again, which works, but I'd be 99% sure that that's an unnecessary step when we already have the bytes available to us.
Slightly c# noob, and every example I've seen about deserializing has involved File objects. Any pointers would obviously be greatly appreciated.
Solution 1:[1]
Be aware that the BinaryFormatter is to be avoided according to official .NET documentation: BinaryFormatter security guide.
Some recommended alternatives are:
XmlSerializerandDataContractSerializerfor serializing/deserializing objects into and from XML;BinaryReaderandBinaryWriterfor XML and JSON data formats;System.Text.JsonAPIs for serializing/deserializing objects into and from memory to JSON.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dina Bogdan |
