Search code examples
c#stringwriterstringreader

Reading and Writing from a txt file?


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.


Solution

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