写对象的列表保存到文件 [英] write list of objects to a file

查看:101
本文介绍了写对象的列表保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的一类业务员:

I've got a class salesman in the following format:

class salesman
{
    public string name, address, email;
    public int sales;
}



我有另一个类,用户输入姓名,地址,电子邮件和销售。然后
该输入添加到列表

I've got another class where the user inputs name, address, email and sales. This input is then added to a list

List<salesman> salesmanList = new List<salesman>();



在用户输入尽可能多的销售员列表后,因为他们喜欢,他们必须保存选项列表以他们所选择的文件(我可以限制的.xml或.txt(其中以往任何时候都更合适))。
我怎么会这个名单添加到文件?
另外这个文件需要,如果用户希望以后查看记录重新读回成一个列表。

After the user has input as many salesman to the list as they like, they have the option to save the list to a file of their choice (which I can limit to .xml or .txt(which ever is more appropriate)). How would I add this list to the file? Also this file needs to be re-read back into a list if the user wishes to later view the records.

推荐答案

这样的事情会工作。这个使用二进制格式(最快加载),但相同的代码将适用与不同的序列化XML。

Something like this would work. this uses a binary format (the fastest for loading) but the same code would apply to xml with a different serializer.

using System.IO;

    [Serializable]
    class salesman
    {
        public string name, address, email;
        public int sales;
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<salesman> salesmanList = new List<salesman>();
            string dir = @"c:\temp";
            string serializationFile = Path.Combine(dir, "salesmen.bin");

            //serialize
            using (Stream stream = File.Open(serializationFile, FileMode.Create))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                bformatter.Serialize(stream, salesmanList);
            }

            //deserialize
            using (Stream stream = File.Open(serializationFile, FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                List<salesman>  salesman = (List<salesman>)bformatter.Deserialize(stream);
            }
        }
    }

这篇关于写对象的列表保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆