Lars Persson

Lars Persson

  • NA
  • 110
  • 0

Saving List of objects to disc.

Apr 16 2012 1:33 PM
I have been trying to save a List to disc and loading it back.

Maybe the some if it is obsolete.

One possibel problem is also that I have a List in one class.

Maybe I have to use Serialization but not really sure when that is needed.

Anyway, here my code. I don't get any errors but it doesn't work.

The folder is made and I can save a .dat-file but I can't load the list.

private void Form1_Load(object sender, EventArgs e
{
      if (!Directory.Exists(dir))
           Directory.CreateDirectory(dir);
           
      BinaryReader customerBinaryIn = new BinaryReader(new FileStream(path, FileMode.OpenOrCreate,         FileAccess.Read));

      while (customerBinaryIn.PeekChar() != -1)   //Så länge det inte är slut på tecken
     {
           Kund kund1 = new Kund();
           kund1.PersonNr = customerBinaryIn.ReadInt32();
           kund1.Name = customerBinaryIn.ReadString();
           CustomerList.Add(kund1);
      }
           
            customerBinaryIn.Close();
}


 public void sparaKund()
 {
           
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
           
            BinaryWriter customerBinaryOut = new BinaryWriter(new FileStream(path, FileMode.Create,  FileAccess.Write));
           
            foreach (Kund K in CustomerList)
            {
                customerBinaryOut.Write(K.PersonNr);
                customerBinaryOut.Write(K.Name);
                customerBinaryOut.Write(K.Loan.ToString()); //Not sure about this...
            }

            customerBinaryOut.Close();
        
 }

private void button1_Click_1(object sender, EventArgs e)    //close button       
{
            
        sparaKund();
        Environment.Exit(1);
       
}





Answers (21)