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.
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.