write list of objects to a file

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>();

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.

Answers


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);
            }
        }
    }

Need Your Help

Yii2 set hidden input as current user id

yii2 yii2-advanced-app

I'm trying to set a form field as the id of the current logged in user using Yii2.

How to merge table row with php array?

php html mysql codeigniter table

I want to merge the teble row if the date have an same id's. I have some array date like this :

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.