0

I am creating a game with c# and i have occurred a problem. I want my game to save curtain labels to a txt file here ill give you a example:

Label1.Text = "Character Name: "
Label2.Text = "Level: "
Label3.Text = "Exp: "

Now what i wanted to do was to retrieve "Character Name: [Name]" From a txt file? But i also wanted to save the name to a txt file when you exit the game. so here might be a better example:

I want to retrieve Level: [LVL] From a txt file and when the gamer has finished and exit my game i want it to overwrite the existing line that was there with there new level?

I think I need to use StringReader or StringWriter.

Alexei Levenkov
  • 94,391
  • 12
  • 114
  • 159
Terrii
  • 365
  • 4
  • 8
  • 23
  • 1
    For really simple I/O, try using the `System.IO.File` class ( http://msdn.microsoft.com/en-us/library/system.io.file.aspx ), especially its `ReadAllText` and `WriteAllText` methods. Once you got that down, you can maybe look at doing things differently or at least move on to tracking when to read/write and how to reload the game. Just be sure to abstract the saving/loading to a separate portion of your program so you can change it willy nilly as need be. – Chris Sinclair Jan 03 '13 at 02:54
  • 1
    I've removed all sort of "thankyou notes"/"don't know how to use samples" from the question... Please add instead code that you can't get working. Side note: consider Xml as it may be easier to read structured data from. – Alexei Levenkov Jan 03 '13 at 02:59
  • thanks ill give it a go i just need a code to read off like an example code i have looked around but i can't find one because i'm blind when writing off codes and i only have 6 months to get this game up and running before my child is born :/ – Terrii Jan 03 '13 at 03:01
  • Or you can simply serialize everything on closing, and deserialize them on opening http://msdn.microsoft.com/en-us/library/4abbf6k0.aspx – Martheen Jan 03 '13 at 03:02

5 Answers5

2

Here's a quick sample using XML serialization with a data model. Make sure you have a using System.Xml.Serialization; namespace import line at the top of your file.

Declare the data you wish to save/load as a simple class, for example:

public class SaveData
{
    public string CharacterName { get; set; }
    public int Level { get; set; }
    public int Experience { get; set; }
}

When you want to save, build that data model:

SaveData saveState = new SaveData()
{
    CharacterName = myCharacter.Name,
    Level = myCharacter.Level,
    Experience = myCharacter.Experience
};

To save to a file, use the XmlSerializer class and open a stream to a file to serialize it to:

public void SaveStateToFile(SaveData state)
{
    XmlSerializer serializer = new XmlSerializer(typeof(SaveData));
    using (TextWriter writeFileStream = new StreamWriter(@"C:\savefile.xml"))
    {
        serializer.Serialize(writeFileStream, state);
    }
}

That will create an xml file with the following content for example:

<?xml version="1.0" encoding="utf-8"?>
<SaveData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <CharacterName>John</CharacterName>
  <Level>10</Level>
  <Experience>9001</Experience>
</SaveData>

So that should be pretty easy to edit if needed. To load the data back:

public SaveData LoadStateFromFile()
{
    XmlSerializer serializer = new XmlSerializer(typeof(SaveData));
    using (FileStream readFileStream = new FileStream(@"C:\savefile.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        return (SaveData)serializer.Deserialize(readFileStream);
    }
}

That should give you a nice type-safe data model to then rebind your GUI as desired:

SaveData loadedData = LoadStateFromFile();
Console.WriteLine(loadedData.CharacterName); //John
Console.WriteLine(loadedData.Level); //10
Console.WriteLine(loadedData.Experience); //9001

Label1.Text = "Character Name: " + loadedData.CharacterName;
Label2.Text = "Level: " + loadedData.Level;
Label3.Text = "Exp: " + loadedData.Experience;
Chris Sinclair
  • 21,634
  • 3
  • 47
  • 88
  • Wow thank you so so much this is exactly what i needed! you are amazing! if i could do anything else to give you some kind of credit on this website i would, in my game i will gladly put your name and link down, thank you! – Terrii Jan 03 '13 at 03:41
  • It has a error is can't find myCharacter.Name, Level = myCharacter.Level or myCharacter.Experience – Terrii Jan 03 '13 at 03:44
  • @Terrii Place there wherever you're storing that data in general. I'm assuming you have some character object somewhere that's storing those properties. – Chris Sinclair Jan 03 '13 at 04:18
  • nope, you create your own character and then it sends you to a new form the main windows then on startup it loads the username you picked and then your lvl = 0 and then your experience = 0 then when you exit i wanted to save that data to an xml file i don't have a character file. – Terrii Jan 03 '13 at 04:23
  • the xml was going to be there savefile so there character file – Terrii Jan 03 '13 at 04:24
  • should i make a data source? – Terrii Jan 03 '13 at 04:25
  • @Terrii No, I'm saying that _somewhere_ in your game you have these variables indicating the username, the level, and experience. So when you level up, _somewhere_ in your game you increment that `level` or increase that `experience`. Those properties you should use for building the `SaveData` data model. – Chris Sinclair Jan 03 '13 at 11:39
1

You may try to use XML for the settings file. Here is a very simple example:

Create a new XML file, fill it with the character name and save:

XElement x = new XElement("Settings");
x.Add(new XElement("CharacterName", "John Doe"));
x.Save("1.xml");

Load the saved xml and print the output:

XElement loaded = XElement.Load("1.xml");
Console.WriteLine(loaded.Element("CharacterName").Value);

Here is an MSDN article to start with:LINQ to XML


If .NetFramework 3.5 and higher is not available, you may use classes from System.Xml namespace. See

  1. XML in .NET: .NET Framework XML Classes and C# Offer Simple, Scalable Data Manipulation
  2. Manipulate XML data with XPath and XmlDocument
  3. Writing XML with the XmlDocument class

...just google with C# xmldocument.

horgh
  • 16,280
  • 18
  • 57
  • 114
  • I just tryed that and i'm using windows forms sorry i forgot to describe and i'm using .net frameworks 3 and it can't find XElement – Terrii Jan 03 '13 at 03:08
  • I used console application only for an example. It makes no difference indeed. LINQ minimum framework requirement is 3.5. However you may use [XmlDocument Class](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx) with .NetFramework 3 – horgh Jan 03 '13 at 03:23
  • I just read them and it works thank you very much :) i used this source http://csharp.net-tutorials.com/xml/writing-xml-with-the-xmldocument-class/ – Terrii Jan 03 '13 at 11:21
  • @Terrii glad, it helped you. – horgh Jan 03 '13 at 14:29
0

You can try SQLite. It's database that save in text file. You will have capability to organize your data better than using your own plain text.

Paiboon Panusbordee
  • 771
  • 1
  • 10
  • 25
0

Another option is to use old INI files. Here is a great An INI file handling class using C# example that will help you to deal with that. Here is an example of using it:

Create a INIFile like this

INIFile ini = new INIFile("C:\\test.ini");

Use IniWriteValue to write a new value to a specific key in a section or use IniReadValue to read a value FROM a key in a specific Section.

Vlad Bezden
  • 59,971
  • 18
  • 206
  • 157
0

This is the code i ended up using and it works fine:

XmlDocument xmlDoc = new XmlDocument();
XmlNode rootNode = xmlDoc.CreateElement("Info");
xmlDoc.AppendChild(rootNode);

XmlNode userNode = xmlDoc.CreateElement("Username");
userNode.InnerText = Username.Text;
rootNode.AppendChild(userNode);

xmlDoc.Save(gameFolder + Username.Text + ".sav");

I used the sources from @Konstantin Vasilcov

Terrii
  • 365
  • 4
  • 8
  • 23