1

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.

4
  • but I would like there to be several Person objects ... this doesn't reflect your title. Your question doesn't relate to constructing objects.. it relates to serialization to a file. Commented Nov 2, 2019 at 12:46
  • Hi Rayane. For maintainable code I recommend you write your code in English - both variable names and comments. I assume you meant to serialize/deserialize a list of Person, not a Person. Commented Nov 2, 2019 at 12:47
  • Yes, I'm sorry, I was wrong, but I need both. Commented Nov 2, 2019 at 12:48
  • there are conditional scenarios here to consider, mostly relating to if the file exists and whether you're looking to append data or write the entirety of a collection of data. it relates to the formatter as well. with BinaryFormatter, I'm unsure whether the concept of a collection\array of data is stored in the file. If this were a file where each newline represented a new record, you would simply append the data on a new line at the end of the file, so to speak. So, there is an underline consideration to the stream position, format and desired operation and handling here. Commented Nov 2, 2019 at 13:51

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

That must be it! A list! Thank you I hadn't thought of that I'll see!
Hmm how can I add a value to my list knowing what is initialized in another form? public List<object> Contacts { get; set; }
Thank you so much! And to deserialize the data, how am I supposed to do that?
Oh no, it's a mistake:(
I was not sure what was OP wanted one file for each or one file for all of the contracts. Anyway, I'll update the answer soon.
|
1

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.

1 Comment

the static function usage here reflects my testing setup. it isn't a recommendation or suggestion for your implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.