c# - 如何保存人类可读的文件

标签 c# .net xml-serialization

目前我有一个应用程序,它使用二进制序列化程序从一个或两个基本类读取和写入多个属性到一个 .txt 文件。

我已经在记事本中打开了 .txt 文件,因为它是为应用程序格式化的,所以人眼可读性不是很好,反正对我来说不是 =D

我听说过使用 XML,但我的大多数搜索似乎都使事情过于复杂。

我试图保存的数据类型只是“Person.cs”类的集合,只不过是名称和地址,所有私有(private)字符串,但具有属性并标记为可序列化。

以人们可以轻松读取的方式实际保存我的数据的最佳方式是什么?它还可以更轻松地直接在文件中对应用程序的数据进行小的更改,而不必加载、更改和保存它。

编辑:

我添加了当前保存和加载数据的方式,我的 _userCollection 就像它建议的那样,nUser/nMember 是一个整数。

#region I/O Operations

    public bool SaveData()
    {
        try
        {
            //Open the stream using the Data.txt file
            using (Stream stream = File.Open("Data.txt", FileMode.Create))
            {
                //Create a new formatter
                BinaryFormatter bin = new BinaryFormatter();
                //Copy data in collection to the file specified earlier
                bin.Serialize(stream, _userCollection);
                bin.Serialize(stream, nMember);
                bin.Serialize(stream, nUser);
                //Close stream to release any resources used
                stream.Close();
            }
            return true;
        }
        catch (IOException ex)
        {
            throw new ArgumentException(ex.ToString());
        }
    }

    public bool LoadData()
    {
        //Check if file exsists, otherwise skip
        if (File.Exists("Data.txt"))
        {
            try
            {
                using (Stream stream = File.Open("Data.txt", FileMode.Open))
                {
                    BinaryFormatter bin = new BinaryFormatter();

                    //Copy data back into collection fields
                    _userCollection = (List<User>)bin.Deserialize(stream);
                    nMember = (int)bin.Deserialize(stream);
                    nUser = (int)bin.Deserialize(stream);
                    stream.Close();

                    //Sort data to ensure it is ordered correctly after being loaded
                    _userCollection.Sort();
                    return true;

                }
            }
            catch (IOException ex)
            {
                throw new ArgumentException(ex.ToString());
            }
        }
        else
        {
            //Console.WriteLine present for testing purposes
            Console.WriteLine("\nLoad failed, Data.txt not found");
            return false;
        }
    }

最佳答案

用 XMLSerializer 替换 BinaryFormatter 并运行完全相同的代码。

您需要做的唯一更改是 BinaryFormatter 采用空构造函数,而对于 XMLSerializer,您需要在构造函数中声明类型:

XmlSerializer serializer = new XmlSerializer(typeof(Person));

关于c# - 如何保存人类可读的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1977315/

相关文章:

.net - XmlSerializer : remove unnecessary xsi and xsd namespaces

c# - 如何使用自定义授权扩展连接到 SSRS API

c# - SSL/TLS/HTTPS 站点在 C#/.NET WebBrowser 控件中非常慢,但在 Internet Explorer 中正常

c# - 从链接的 dll 读取 app.exe.config 文件设置的简单方法

c# - 为什么许多 XML 序列化示例会去除特定字符?

java - SimpleXml 框架 - 嵌入式集合

c# - 正则表达式特周

c# - 子弹变成弹孔

c# - 实现组合的正确方法(带有接口(interface)的组合)

c# - 正则表达式找不到所有匹配项