Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I save variables to a new text file so that those variables are loaded the next time the program runs?

Tags:

c#

console

save

new C#er here. I'm making a console based RPG. It's coming along quite well, but I need to find out how to save the game. I would guess that there is a way to save variables from my app into a text file that can be used to load the variables when the application is run again. Unfortunately I have no idea where to start.

Also I need a way to go to a point in the code when loading a save file.

Some of my variables include:

int xCoordinate, yCoordinate, hp, hpmax, level;

Any sample code would be greatly appreciated.

like image 961
Jared Price Avatar asked Jan 15 '23 00:01

Jared Price


2 Answers

It is simple to write some variables to a text file:

TextWriter tw = new StreamWriter("SavedGame.txt");

// write lines of text to the file
tw.WriteLine(xCoordinate);
tw.WriteLine(yCoordinate);

// close the stream     
tw.Close();

And read them back in:

// create reader & open file
TextReader tr = new StreamReader("SavedGame.txt");

// read lines of text
string xCoordString = tr.ReadLine();
string yCoordString = tr.ReadLine();

//Convert the strings to int
xCoordinate = Convert.ToInt32(xCoordString);
yCoordinate = Convert.ToInt32(yCoordString);

// close the stream
tr.Close();
like image 160
dave823 Avatar answered Jan 30 '23 23:01

dave823


You can use binary serialization to accomplish this fairly easily. First, create a class containing all the variables you want to write:

[Serializable]
class Data
{
    int x;
    int y;
}

Then use it as follows:

Data data = new Data();

//Set variables inside data here...

// Save data
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = File.OpenWrite("C:\\Temp\\bin.bin"))
{
    formatter.Serialize(stream, data);
}
like image 43
Steve Westbrook Avatar answered Jan 31 '23 00:01

Steve Westbrook