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

Rails 3 multiple parameter filtering using scopes

ruby-on-rails ruby-on-rails-3

Trying to do a basic filter in rails 3 using the url params. I'd like to have a white list of params that can be filtered by, and return all the items that match. I've set up some scopes (with many...

How do I change find result highlight color with VS2010 and Resharper?

visual-studio-2010 resharper

I just installed Resharper and it's changed the highlight color for find results. Normally when I place my cursor on a particular symbol, say a variable called 'goat', all onscreen references to goat

Creating a measurement bar in WPF

c# .net wpf design controls

I'm working on a measurement system and I need to represent to the user the measure level in a nice graphical way. I designed a measurement bar in Photoshop and I'm now trying to implement it in WP...