简体   繁体   English

从txt文件读取和写入?

[英]Reading and Writing from a txt file?

I am creating a game with c# and i have occurred a problem. 我正在用C#创建游戏,但发生了问题。 I want my game to save curtain labels to a txt file here ill give you a example: 我想让我的游戏将窗帘标签保存到txt文件中,请举个例子:

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? 现在我想做的是从txt文件中检索“字符名称:[名称]”? But i also wanted to save the name to a txt file when you exit the game. 但是我也想在退出游戏时将名称保存到txt文件中。 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? 我想从一个txt文件中检索级别:[LVL],并且当玩家完成游戏并退出游戏时,我希望它覆盖存在新级别的现有行吗?

I think I need to use StringReader or StringWriter . 我想我需要使用StringReaderStringWriter

Here's a quick sample using XML serialization with a data model. 这是将XML序列化与数据模型结合使用的快速示例。 Make sure you have a using System.Xml.Serialization; 确保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: 若要保存到文件,请使用XmlSerializer类并打开文件流以将其序列化为:

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文件,例如:

<?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: 那应该给你一个很好的类型安全的数据模型,然后根据需要重新绑定GUI:

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;

You may try to use XML for the settings file. 您可以尝试将XML用于设置文件。 Here is a very simple example: 这是一个非常简单的示例:

Create a new XML file, fill it with the character name and save: 创建一个新的XML文件,用字符名填充并保存:

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

Load the saved xml and print the output: 加载保存的xml并打印输出:

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

Here is an MSDN article to start with: LINQ to XML 这是MSDN文章的开头: LINQ to XML


If .NetFramework 3.5 and higher is not available, you may use classes from System.Xml namespace. 如果.NetFramework 3.5及更高版本不可用,则可以使用System.Xml命名空间中的类。 See 看到

  1. XML in .NET: .NET Framework XML Classes and C# Offer Simple, Scalable Data Manipulation .NET中的XML:.NET Framework XML类和C#提供简单,可伸缩的数据操作
  2. Manipulate XML data with XPath and XmlDocument 使用XPath和XmlDocument处理XML数据
  3. Writing XML with the XmlDocument class 使用XmlDocument类编写XML

...just google with C# xmldocument . ...只是使用C#xmldocument的 google。

You can try SQLite . 您可以尝试使用SQLite It's database that save in text file. 它是保存在文本文件中的数据库。 You will have capability to organize your data better than using your own plain text. 与使用纯文本相比,您将能够更好地组织数据。

Another option is to use old INI files. 另一种选择是使用旧的INI文件。 Here is a great An INI file handling class using C# example that will help you to deal with that. 这是一个很棒的使用C#示例的INI文件处理类 ,它将帮助您进行处理。 Here is an example of using it: 这是使用它的一个例子:

Create a INIFile like this 像这样创建一个INIFile

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. 使用IniWriteValue将新值写入节中的特定键,或者使用IniReadValue从特定节中的键读取值。

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 我使用了@Konstantin Vasilcov的资料

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM