Reputation: 4897
I've got a custom collection which adds functionality to the 'ArrayList' class.
Here's some code from the class:
[Serializable]
class Coll : ArrayList
{
public void Save(string path)
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream fsOut = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
formatter.Serialize(fsOut, this);
fsOut.Dispose();
}
}
I'm now trying to deserialize a file, and fill the collection with the contents of the file. Basically the opposite of my Save(string path)
method.
This is what I've got so far:
public void Read(string path)
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream fsIn = new FileStream(path, FileMode.Open, FileAccess.Read);
formatter.Deserialize(fsIn);
fsIn.Dispose();
}
How should I go about populating the collection with the contents which has been deserialized?
Upvotes: 0
Views: 203
Reputation: 1062945
BinaryFormatter
doesn't support serialising into an existing object. You could deserialize it into a new list - just make it a static
method and return the value.
Other thoughts:
ArrayList
unless you are in .net 1.1: List<T>
would be preferableBinaryFormatter
for this... Or anything else reallyUpvotes: 2
Reputation: 9445
The method BinaryFormatter.Deserialize() creates a new object, initializes it with the data from the stream and returns it. Therefore, you should use the return value and use it as the new ArrayList
object. The Read
method thus goes into a static method, or -- as diggingforfire suggested -- into another class.
Upvotes: 1