Update object of a serialized file

Asked

Viewed 951 times

2

I am having difficulty updating the amount of a recovered object in a list of a serialized file.

    private void button1_Click(object sender, EventArgs e)
    {

        Estoque produtoEstoque = new Estoque();
        produtoEstoque.P = (Produto) comboBox1.SelectedItem;
        produtoEstoque.Quantidade = (int) numericUpDown1.Value;

        FileStream fs = new FileStream("estoque.xyz", FileMode.OpenOrCreate, FileAccess.Read);
        BinaryFormatter bf = new BinaryFormatter();

        List<Estoque> estoque = new List<Estoque>();
        if (fs.Length != 0)
        {
            estoque = (List<Estoque>)bf.Deserialize(fs);
        }
        estoque.Add(produtoEstoque);
        fs.Close();

        FileStream fs2 = new FileStream("estoque.xyz", FileMode.OpenOrCreate, FileAccess.ReadWrite);
        BinaryFormatter bf2 = new BinaryFormatter();

        bf2.Serialize(fs2, estoque);
        fs2.Close();

        MessageBox.Show("Compra salva com sucesso!");
  • You’ve been getting an error?

  • Yes, before adding a new element to the stock list, I need for example to check if the item already exists and if it exists, I just need to change the quantity attribute. For this I made a foreach to check if the item already exists, it is precisely in foreache that gives the error. I did it after the if to deserialize. The error is this: An unhandled Exception of type 'System.Invalidoperationexception' occurred in mscorlib.dll Additional information: Collection has been modified; maybe the enumeration operation will not be executed.

  • Please edit your question by adding the error.

  • Enter the foreach code, which I believe is the most relevant to your problem. But by the error described, you are modifying a collection within a foreach. I suggest switching to a common for that can already solve.

  • You cannot modify a collection (add/remove) by foreach it

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.