如何保存人类可读文件

Jam*_*ing 2 .net c# xml-serialization

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

我在NotePad中打开了.txt文件,因为它为应用程序格式化,它对人眼来说不是很易读,不管怎样对我来说= D

我听说过使用XML,但我的大部分搜索工作似乎都过于复杂.

我试图保存的数据类型只是"Person.cs"类的集合,只不过是名称和地址,所有私有字符串但具有属性并标记为Serializable.

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

编辑:

我添加了当前保存和加载数据的方式,我的_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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Yur*_*ich 6

用XMLSerializer替换BinaryFormatter并运行相同的确切代码.

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

XmlSerializer serializer = new XmlSerializer(typeof(Person));
Run Code Online (Sandbox Code Playgroud)