c# - write list of objects to a file -
i've got class salesman in following format:
class salesman { public string name, address, email; public int sales; }
i've got class user inputs name, address, email , sales. input added list
list<salesman> salesmanlist = new list<salesman>();
after user has input many salesman list like, have option save list file of choice (which can limit .xml or .txt(which ever more appropriate)). how add list file? file needs re-read list if user wishes later view records.
something work. uses binary format (the fastest loading) same code apply xml 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); } } }
Comments
Post a Comment