Link to home
Create AccountLog in
Avatar of jackjohnson44
jackjohnson44

asked on

serialize a class write to file

I am going to be using c# to write the contents of a class to a text file.  I want to just append to the file each time I write.

I want to get the contents back by reading the classes (all the same) into a generic list.

1.  How can I write to the file?
2. How can I read back from the file into a list?
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

You can store into an XML file.
XmlSerializer xs = new XmlSerializer(typeof(yourListclass));
xs.Serialize(yourfilestream, yourListobject);
if you want to deserialize use:
yourListobject = (yourListClass) xs.Deserialize(yourfilestream);
Avatar of jackjohnson44
jackjohnson44

ASKER

thanks, but what if I keep appending to my text file?  Will the list work?  What I mean is I am not putting a list into a text file.  I am putting classes in a text file and want a list out.

I guess I could read the whole thing into a list, add to the list, then write back, but I would rather just append.
ASKER CERTIFIED SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
I am gettting this error:

---------------------------

---------------------------
System.InvalidOperationException: There is an error in XML document (0, 0). ---> System.Xml.XmlException: Root element is missing.

   at System.Xml.XmlTextReaderImpl.Throw(Exception e)

   at System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res)

   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()

   at System.Xml.XmlTextReaderImpl.Read()

   at System.Xml.XmlTextReader.Read()

   at System.Xml.XmlReader.MoveToContent()

   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read6_ArrayOfRNetFileEvent()

   --- End of inner exception stack trace ---

   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)

   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)

   at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)

   at RNetWordAddIn.ThisAddIn.GetFileInformation(Document Doc) in C:\Ihi2\SharePoint\OfficeTools\WordAddIn\ThisAddIn.cs:line 62
---------------------------
OK  
---------------------------