【发布时间】:2020-10-25 15:24:29
【问题描述】:
作为一个教程项目,我必须使用 c# 创建一个咖啡机模拟器。我已经成功完成了这个项目,但我希望将变量的内容写入文件,以便用户无需再次设置。我已经尝试过 Microsoft 的演示项目:
using System;
using System.Linq;
using System.IO;
using System.Reflection.Metadata;
using System.Text;
namespace TestingCode
{
class Program
{
public static void Main()
{
string path = "Test.txt";
try
{
// Create the file, or overwrite if the file exists.
using (FileStream fs = File.Create(path))
{
Console.WriteLine("Enter a string:");
string input = Console.ReadLine();
byte[] info = new UTF8Encoding(true).GetBytes(input);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
此代码成功运行并将用户输入的值写入文本文件。请任何人都可以帮我将变量写入文本文件并从中读取。
谢谢, 王者荣耀266
【问题讨论】:
-
input也是可变的,您正在写入它的值。你也可以使用File.Write和File.Read -
将变量写入文件到底是什么意思?如果您正在寻找持久化对象的状态,那么您应该查看 json 或 xml 序列化。