CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2001
    Location
    Newcastle Ontario, Canada
    Posts
    118

    Quick Serialization

    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

  2. #2
    Join Date
    May 2002
    Location
    Florida USA
    Posts
    27
    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

  3. #3
    Join Date
    Jun 2001
    Location
    Newcastle Ontario, Canada
    Posts
    118
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured