Click to See Complete Forum and Search --> : Quick Serialization


Steve Scott
September 4th, 2002, 10:57 PM
Im not sure how serialization works. This is just a newbie question.

Lets say I have 25 objects...can they easily be individually written and read from a single file? I can only have one of these classes instantiated at a time, so I need to save the previous one before I create another. But im not sure how the file 'looks'. for example can I just say

Save(object1);
then just as easily (I know these functions dont exist...just theory)
Load(object1);
Load(object2);
...etc

Any info would be appreciated,
Thanks,
Steve

bfarley
September 5th, 2002, 05:31 AM
FileStream fs= new FileStream("filename", FileMode.Open, FileAccess.Write);

if(fs!= null){
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, myobjectlist);
fs.Close();
}
This will save the collection (myobjectlist) to one file ("filename").

FileStream fs= new FileStream("filename", FileMode.Open, FileAccess.Read);

if(fs!= null){
BinaryFormatter bf = new BinaryFormatter();
myobjectlist= bf.Deserialize(fs) as ArrayList;
fs.Close();
}
This will retrieve the collection (assumes myobjectlist is an ArrayList). EZ cheezee.

Saving single object to the same file one at a time is more problematic, Serialize was designed to be used with collections. If you really need to save one at a time, I would just use separate files.

Bill F

Steve Scott
September 5th, 2002, 01:06 PM
Seperate files arn't an option...theres 25 seperate classes, so if they save 2 people then there would be 50 files...etc

Can you not just do bf.Serialize(fs, myObject); ?

Steve