Deselect list C # objects

1

I'm trying to put together a simple program to practice what I've seen in the faculty, it's some xml files. The program is made in windows forms, and I need to get it to store objects of my own class, but I have a problem when I try to perform, the file is serialized in another part of the program, and I think it's fine, the file is created but not I can load the data in my list of objects.

            public Form1()
            {
                InitializeComponent();
            }

            Resumen resumen = new Resumen(); //Lista de mi clase donde guardo los objetos.

            private void button1_Click(object sender, EventArgs e)
            {
                Form2 f = new Form2(resumen); //le paso la lista donde guardar objetos al formulario que guarda los datos en el xml
                f.Show();
            }

        private void button2_Click(object sender, EventArgs e)
                    {
                        try
                        {
                            //Cuenta c = new Cuenta();

                            XmlSerializer serializador = new XmlSerializer(resumen.GetType());
                            FileStream archivo = new FileStream("D:\Resumendecuenta.xml", FileMode.Open, FileAccess.Read);
     //el archivo lo busco en "D:\.." aunque originalmente no lo guarde ahi  cuando serializo, 
    //copie el archivo y lo pegue manualmente ahi.

                            resumen = (Resumen)serializador.Deserialize(archivo);  //<-- Aca es donde tengo el error! me dice invalidOperationExeption.
//Información adicional: Error en el documento XML (13, 13). (eso dice)

                            archivo.Close();

                            //r += c;

                            richTextBox1.Text = resumen.Mostrar();
                        }
                        catch (FileNotFoundException)
                        {
                            MessageBox.Show("Se ha producido un error", "Error en el archivo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

This is the other part where I save and generate the xml.

Resumen resumen = new Resumen();
        public Form2(Resumen r)
        {
            InitializeComponent();
            resumen = r;
        }

private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    DialogResult result; //Variable para guardar una seleccion de MessageBox.

                    //do
                    //{

                        Cuenta cuenta = new Cuenta(textBox1.Text, float.Parse(textBox2.Text)); //creo una cuenta con sus respectivos valores.

                        //resumen += cuenta; //agrego una cuenta al resumen.
                        resumen.resumen.Add(cuenta);

                        FileStream archivo = new FileStream("Resumendecuenta.xml", FileMode.Create, FileAccess.Write); //creo un archivo xml.

                            XmlSerializer serializable = new XmlSerializer(resumen.GetType()); //creo el serializador.
                            serializable.Serialize(archivo, resumen); //serializo

                        archivo.Close(); //cierro el xml

                        //Muestro mensaje de creacion exitosa y capturo la seleccion.
                        result = MessageBox.Show("Cuenta guardada exitosamente! ¿Desea guardar otra cuenta?", "Mensaje", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);

                        //Limpio los textBox para ingresar nuevamente datos.
                        if (result == DialogResult.Yes) {
                            textBox1.Clear();
                            textBox2.Clear();
                        }
                    //} while (result != DialogResult.No); //Se repite mientras el usuario seleccione 'Si'.

                    Close(); //cierro el formulario.
                }
                catch (FormatException)
                {
                    MessageBox.Show("Ups! Se ha producido un error", "Formato Invalido", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

My query is basically if I'm performing well, I get the error invalidOperationExeption Additional information: Error in the XML document (13, 13). when I try to show the deseralizados data that I try to keep in the list with objects of my class

Account and Summary are two own classes, Summary only has the List and Account has two attributes, name and amount, with their respective get and set (in properties). The small parts of the commented code are of things that I wanted to add but I did not achieve the proper functionality, it only matters what is not commented.

    
asked by Lucas Medina 31.05.2017 в 17:17
source

1 answer

0

Most likely either that you are doing wrong the reference to the file or it is being used by some process.

Here I leave you my console version but using your code as a reference.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization;

    namespace ErrorSerializacion
    {
        public class Program
        {
            private static string rutaArchivoXML = @".\Resumendecuenta.xml";

            static void Main(string[] args)
            {
                GenerarXML();

                ObtenerXML();

                Console.ReadKey();
            }

            public static void ObtenerXML()
            {
                try
                {
                    Console.WriteLine("***** ObtenerXML:");

                    Resumen resumen = new Resumen();

                    XmlSerializer serializador = new XmlSerializer(typeof(Resumen));
                    FileStream archivo = new FileStream(rutaArchivoXML, FileMode.Open, FileAccess.Read);

                    resumen = (Resumen)serializador.Deserialize(archivo);

                    archivo.Close();

                    if (resumen != null && resumen.Listado != null && resumen.Listado.Count > 0)
                    {
                        Console.WriteLine(resumen.Listado[0].Cadena + " - " + resumen.Listado[0].Flotante);
                    }
                    else
                    {
                        Console.WriteLine("resumen vacio o nulo.");
                    }
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.ToString());
                }
            }

            public static void GenerarXML()
            {
                try
                {
                    Console.WriteLine("***** GenerarXML:");
                    Resumen resumen = new Resumen();
                    Cuenta cuenta = new Cuenta("una cuenta", float.Parse("2")); //creo una cuenta con sus respectivos valores.
                    resumen.Listado.Add(cuenta);

                    FileStream archivo = new FileStream(rutaArchivoXML, FileMode.Create, FileAccess.Write); //creo un archivo xml.

                    XmlSerializer serializable = new XmlSerializer(typeof(Resumen)); //creo el serializador.
                    serializable.Serialize(archivo, resumen); //serializo

                    archivo.Close(); //cierro el xml

                    //Muestro mensaje de creacion exitosa y capturo la seleccion.
                    Console.WriteLine("Cuenta guardada exitosamente!");
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Error: " + exc.ToString());
                }
            }
        }

        [Serializable]
        public class Resumen
        {
            private List<Cuenta> _listado;

            public List<Cuenta> Listado
            {
                get
                {
                    return _listado;
                }
                set
                {
                    _listado = value;
                }
            }

            public Resumen()
            {
                this._listado = new List<Cuenta>();
            }
        }

        [Serializable]
        public class Cuenta
        {

            public string Cadena { get; set; }
            public float Flotante { get; set; }

            public Cuenta()
            {
                this.Cadena = string.Empty;
                this.Flotante = 0f;
            }

            public Cuenta(string p1, float p2)
            {
                // TODO: Complete member initialization
                this.Cadena = p1;
                this.Flotante = p2;
            }
        }
    }
    
answered by 31.05.2017 в 20:27