+ 2

Serialization

How to save information from Listview in bin file? When adding new records, I was able to serialize, but I can’t save the existing one

11th Mar 2020, 8:09 AM
Mary_d9
Mary_d9 - avatar
2 ответов
+ 1
How to save information from Listview in bin file? When adding new records, I was able to serialize, but I can’t save the existing one public partial class bibliography : Form { string fileName = "data.dat"; AddBook frm; public bibliography() { InitializeComponent(); } private void OpenFile_Click(object sender, EventArgs e) { var dlg = new OpenFileDialog(); if (dlg.ShowDialog() == DialogResult.OK) { fileName = dlg.FileName; LoadFromFile(); } } private void LoadFromFile() { var f1 = new FileStream(fileName, FileMode.OpenOrCreate); var bf = new BinaryFormatter(); while (f1.Position < f1.Length) { var b = (Book)bf.Deserialize(f1); // сохранение объекта в потоке f AddBookToList(b); } f1.Close(); } private void AddBookToList(Book b) { var item = listView.Items.Add(b.Author); item.SubItems.Add(b.Name); item.SubItems.Add(b.Year.ToShortDateString()); item.SubItems.Add(b.PublishingOffice); } private void MenuAdd_Click(object sender, EventArgs e) { frm = new AddBook(); if (frm.ShowDialog() == DialogResult.OK) { AddBookToList(frm.Book); SaveAdd(frm, e); } } private void SaveAdd(object sender, EventArgs e) { if (listView.Items.Count > 0) { var f1 = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); f1.Position = f1.Length; var bf = new BinaryFormatter(); bf.Serialize(f1, frm.Book); // сохранение объекта в потоке f f1.Close(); }
11th Mar 2020, 8:09 AM
Mary_d9
Mary_d9 - avatar
0
A object is not the same a a text. If you have a text, you can append to it. If you are serializing a object, it is a structure. If you want to save the new state of Book. Create a new file / overwrite the existing one Save the entire object Use FileMode.Open, set f1.Position to 0
11th Mar 2020, 9:04 PM
sneeze
sneeze - avatar