如何将变量保存到新的文本文件中,以便下次程序运行时加载这些变量?

How Do I save variables to a new text file so that those variables are loaded the next time the program runs?(如何将变量保存到新的文本文件中,以便下次程序运行时加载这些变量?)
本文介绍了如何将变量保存到新的文本文件中,以便下次程序运行时加载这些变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有新的 C#er.我正在制作基于控制台的 RPG.它进展顺利,但我需要找出如何保存游戏.我猜想有一种方法可以将我的应用程序中的变量保存到一个文本文件中,该文件可用于在应用程序再次运行时加载变量.不幸的是,我不知道从哪里开始.

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.

我的一些变量包括:

int xCoordinate, yCoordinate, hp, hpmax, level;

任何示例代码将不胜感激.

Any sample code would be greatly appreciated.

推荐答案

将一些变量写入文本文件很简单:

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();

然后将它们读回:

// 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();

这篇关于如何将变量保存到新的文本文件中,以便下次程序运行时加载这些变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)