Plan du site  
pixel
pixel

Articles - Étudiants SUPINFO

Saving objects in C#

Par Rémi BARLAGUET Publié le 28/10/2019 à 09:13:22 Noter cet article:
(0 votes)
Avis favorable du comité de lecture

Presentation

The principle of saving the state of an object or a variable is called serialization. The inverted process, which constitutes in gathering data from a file via the program and storing them into the right place is called deserialization.

In C# programming, there is multiple options to save the state of a program:

- Using a local or an hosted SQL database is interesting, but it is very long to settle for a small program.

- LINQ is a database system designed for C#, which makes it a solution to use in the case when your program isn't advanced, because it can take a long time to settle (like the SQL option above).

- Saving the state of objects and variables on an external could be a solution. The problem is that the save is local, making it easy be modified, corrupted or deleted... Depending of the program, it can cause huge consequences.

- In this case, we will choose the last solution, which is the external file saved locally in the machine of the user. This solution has been chosen because it is the easiest and fastest to use, as the project i am using is almost done, which will permit to add the save without touching the principal structure of the code.

To be clear, we are using a command line interface in this program. I believe it can also work out for programs with graphic interfaces, but it would require using an array of values to keep and compute every value you need for the save.

How does it work ?

In the program you developed, you will need to integrate a saving method, to restore the state of your files and variables. Depending of the program, you can add a verification which will use the save file add context menus on additional content for users that have already been using the application.

Here is what you would bee to integrate at the top of the class file you want to save.

			namespace name_of_your_namespace
			{
				[Serializable] // permit the save autorization the save (serialization).
				class yourClass
				{
					// insert code here
				}
			}
		

The "[Serializable]" code is there to indicate that objects of this class can actually be saved. This is what you will need to add on the top of your main class:

			using System.Runtime.Serialization;
			using System.Runtime.Serialization.Formatters.Binary;
		

To get the path of the folder of the application:

			String appFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase); // path to debug file
		

To get the path of the file where the program is executed, add this in the code:

			String pathToFile = Path.Combine(appFolder, "GameSave.bin");
		

To check if the save file already exist (and a save has already been done):

			if(File.Exists(Directory.GetCurrentDirectory() + @'\GameSave.bin")) // if a player save is already present
			{
				//insert code here
			}
		

The verification will happen in the Debug folder of the program. This is where we find the .exe of the program. In the case where the save file exist and we want to restore its state, you need to add:

			if (save == 1)
			{
				IFormatter formatterRestoration = new BinaryFomatter();
				Stream streamRestoration = new FileStream("GameSave.bin",
					FileMode.Open,
					FileAccess.Read,
					FileShare.Read);
				playerSave = (Player) formatterRestoration.Deserialize(streamRestoration);
				
				streamRestoration.Close();
			}
		

These lines will permit you to retrieve the file "GameSave.bin", which will reintegrate the state of the object and variables if it is read (deserialize). For me, in this case, I was using the "playerSave", which is an object of the type Player (a class containing attributes, dependencies, heritages, etc...).

At this state, we have an Object that contains values restaured from the created file. This is the part of the code used to create the saved state of my "Player" object.

			if (choice == "1") // the player want to save the state of the game before leaving.
			{
				//serialize the player object (we save the state before leaving the console app).
				IFormatter formatter = new BinaryFormatter(); //binFormatter
				Stream stream = new FileStream("GameSave.bin", FileMode.Create, FileAccess.Write, FileShare.None);
				formatter.Serialize(stream, player);
				stream.Close();
				Console.WriteLine("\nYour game was successfully saved !");
			}
		

You are free to save whatever you want. If you have multiple objects or elements to save, you can stack them up into an array, then push/get this array and iterate into it to retrieve the different data you want to save.

Conclusion

Among all the possible choices to save our program, we covered the most simple one. It can be easily used without changing any major part of your code, or just by adding the values you want to save into the file by filling a variable or an array.

To learn more about C# or to learn how to develop your skills to get to the next level and work with graphical interfaces, you can check guides online. It will help you learning how to use libraries, learning new coding tricks or simply help you developing your learning new functionalities. One of the best websites for that could be codeacademy, which offers videos to help you developing your developing skills.

A propos de SUPINFO | Contacts & adresses | Enseigner à SUPINFO | Presse | Conditions d'utilisation & Copyright | Respect de la vie privée | Investir
Logo de la société Cisco, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société IBM, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Sun-Oracle, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Apple, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Sybase, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Novell, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Intel, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Accenture, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société SAP, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Prometric, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Toeic, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo du IT Academy Program par Microsoft, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management

SUPINFO International University
Ecole d'Informatique - IT School
École Supérieure d'Informatique de Paris, leader en France
La Grande Ecole de l'informatique, du numérique et du management
Fondée en 1965, reconnue par l'État. Titre Bac+5 certifié au niveau I.
SUPINFO International University is globally operated by EDUCINVEST Belgium - Avenue Louise, 534 - 1050 Brussels