Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 200
Pindo Avatar asked May 03 '13 06:05

Pindo


1 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);             }         }     } 
like image 65
Matt Johnson Avatar answered Oct 10 '22 02:10

Matt Johnson