Rayane Staszewski
Rayane Staszewski

Reputation: 122

Creating objects and object serialization in C#

I'm a beginner in C# and I created a Person class, which includes more variable and a constructor:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Contact
{
    [Serializable()] //On peut le sérializer    
    class Personne
    {
        //Constructeur
        public Personne(string prenom, string nom, int age, string dateNaissance, bool isMan, string notes, string pathImage, string mail, 
            string mail2, string tel, string telFix, string site, string rue, string ville, string numero, string codePostal, string departement)
        {
            Prenom = prenom;
            Nom = nom;
            Age = age;
            DateNaissance = dateNaissance;
            IsMan = isMan;
            Notes = notes;
            this.pathImage = pathImage;
            this.mail = mail;
            this.mail2 = mail2;
            this.tel = tel;
            this.telFix = telFix;
            this.site = site;
            this.rue = rue;
            this.ville = ville;
            this.numero = numero;
            this.codePostal = codePostal;
            this.departement = departement;
        }

        public override string ToString()
        {
            return base.ToString();
        }

        //Variables
        public string Prenom { get; set; }
        public string Nom { get; set; }
        public int Age { get; set; }
        public string DateNaissance { get; set; }
        public bool IsMan { get; set; }
        public string Notes { get; set; }
        public string pathImage { get; set; }
        public string mail { get; set; }
        public string mail2 { get; set; }
        public string tel { get; set; }
        public string telFix { get; set; }
        public string site { get; set; }
        public string rue { get; set; }
        public string ville { get; set; }
        public string numero { get; set; }
        public string codePostal { get; set; }
        public string departement { get; set; }
    }
}

The creation of an object of this class is done here, when pressing a button on my form:

private void Btn_valider_Click(object sender, EventArgs e)
{

                //Création de l'objet
                Personne contact = new Personne(Prenom, Nom, Age, dateNaissanceStr, isMan, notesStr, pathImage, mail, mail2, tel, telFix,
                    site, rue, ville, numero, codePostal, departement);

                //Sauvegarde l'objet
                Stream fichier = File.Create(@"contact.dat");
                BinaryFormatter serializer = new BinaryFormatter();
                serializer.Serialize(fichier, contact);
                fichier.Close();

                this.Close();
            }
            catch
            {
                MessageBox.Show("Erreur.");
            }
        }
    }
}

So, as we can see, I create a contact object (I make a contact manager), but I would like there to be several Person objects, because we don't have only one contact. But if I recreate an object, my serialiser only takes the last one created and I would like to recover ALL the objects.

Upvotes: 1

Views: 1576

Answers (2)

Brett Caswell
Brett Caswell

Reputation: 1504

in regards to my comment, there are several thing to consider here (and thus several implementations at it relates to those considerations).


This answer is going to use Deserialization and Serialization on a List<Personee> type with conditional checks on whether the file exists before serializing.

Mock Data

[Serializable]
public class Personee
{
    public string Prenom { get; set; }
    public string Nom { get; set; }
    public int Age { get; set; }
    public string DateNaissance { get; set; }
    public bool IsMan { get; set; }
    public string Notes { get; set; }
    public string pathImage { get; set; }
    public string mail { get; set; }
    public string mail2 { get; set; }
    public string tel { get; set; }
    public string telFix { get; set; }
    public string site { get; set; }
    public string rue { get; set; }
    public string ville { get; set; }
    public string numero { get; set; }
    public string codePostal { get; set; }
    public string departement { get; set; }
}

public static string FilePath = @"contacts.dat";

public static void RunSample()
{
    Button_Click(null, null);
}

Sample

public static void Button_Click(object sender, EventArgs args)
{
    var personee = new Personee
    {
        Prenom = "Prenom",
        Nom = "Nom",
        Age = 21,
        DateNaissance = "DateNaissance",
        IsMan = true,
        Notes = "Notes",
        pathImage = "pathImage",
        mail = "mail",
        mail2 = "mail2",
        tel = "tel",
        telFix = "telFix",
        site = "site",
        rue = "rue",
        ville = "ville",
        numero = "numero",
        codePostal = "codePostal",
        departement = "department"
    };

    SeralizePersoneeDataFile(personee);
}

public static void SeralizePersoneeDataFile(Personee personee)
{
    SeralizePersoneeDataFile(new Personee[] { personee });
}

public static void SeralizePersoneeDataFile(IEnumerable<Personee> personees)
{
    var personeeDataList = (File.Exists(FilePath))
        ? DeseralizePersoneeDataFile()
        : new List<Personee>();

    personeeDataList.AddRange(personees);

    using (FileStream fichier = File.OpenWrite(FilePath))
    {
        BinaryFormatter serializer = new BinaryFormatter();
        serializer.Serialize(fichier, personeeDataList);
    }
}

public static List<Personee> DeseralizePersoneeDataFile()
{
    using (FileStream fichier = File.OpenRead(FilePath))
    {
        BinaryFormatter serializer = new BinaryFormatter();
        return (serializer.Deserialize(fichier) as List<Personee>);
    }
}

The Deserialization before serialization is necessary here because this serialization implementation writes the entire contents to the file (does not append). That is, if you have 100 contacts in the data file, and then just write 1 record in this manner, it will clear the file and only save the 1.

Upvotes: 1

Farhad Rahmanifard
Farhad Rahmanifard

Reputation: 688

You can create a List<Personne> and save them in the file using a foreach loop.
Your "Btn_valider_Click" method will be something like this:

private void Btn_valider_Click(object sender, EventArgs e)
{
        var personList = new List<Personne>();

        //Création de l'objet
        Personne contact = new Personne(Prenom, Nom, Age, dateNaissanceStr, isMan, notesStr, pathImage, mail, mail2, tel, telFix,
            site, rue, ville, numero, codePostal, departement);

        personList.Add(contact);
        //Adding other persons


        foreach(var cont in personList)
        {
            //Sauvegarde l'objet
            Stream fichier = File.OpenWrite(@"contacts.dat");
            BinaryFormatter serializer = new BinaryFormatter();
            serializer.Serialize(fichier, cont);
            fichier.Close();
        }

        this.Close();
    }
    catch
    {
        MessageBox.Show("Erreur.");
    } 
}

UPDATE: You should consider designing a file structure (how contracts are placed in the file). I am not sure that your serialization provides all the data which is needed for retrieving records from the file. Anyway, writing to the file should be okay now.

Upvotes: 2

Related Questions