【问题标题】:Is there a recommended way of writing the contents of variables to a text file?有没有推荐的方法将变量的内容写入文本文件?
【发布时间】: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.WriteFile.Read
  • 将变量写入文件到底是什么意思?如果您正在寻找持久化对象的状态,那么您应该查看 json 或 xml 序列化。

标签: c# .net-core mono


【解决方案1】:

编辑:您可以使用 nugget 包管理器安装 Newtonsoft.Json

我能想到的最快最简单的方法是使用 Newtonsoft.Json 来序列化数据

创建一个类来存储你的变量: 假设我们有一个模型类来存储我们的变量

public class Model
{
        public int Variable1;
        public string Variable2;
        public List<string> Variable3;
}

这是我们要序列化的对象:

Model m = new Model()
{
    Variable1 = 1,
    Variable2 = "test test",
    Variable3 = new List<string>() { "list element 1 ", "list element 2", "list element 3"}
};

要序列化此对象,请调用 JsonConvert.SerializeObject 并将您的对象作为参数 在我们的例子中,它的输出是一个 json 字符串:

{"Variable1":1,"Variable2":"test test","Variable3":["list element 1","list element 2","list element 3"]}

var serializedData = JsonConvert.SerializeObject(m);

将字符串保存到文件并再次读回

File.WriteAllText("serialized.txt", serializedData);
var loadedData = File.ReadAllText("serialized.txt");

通过调用 JsonConvert.DeserializeObject(yourObject); 将读取的字符串转换回对象

var loadedObject = JsonConvert.DeserializeObject<Model>(loadedData);

完整示例:

static void Main(string[] args)
{
    Model m = new Model()
    {
        Variable1 = 1,
        Variable2 = "test test",
        Variable3 = new List<string>() { "list element 1 ", "list element 2", "list element 3" }
    };

    var serializedData = JsonConvert.SerializeObject(m);

    File.WriteAllText("serialized.txt", serializedData);

    var loadedData = File.ReadAllText("serialized.txt");
    var loadedObject = JsonConvert.DeserializeObject<Model>(loadedData);
}

【讨论】:

    猜你喜欢
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2019-05-12
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多