If you want to serialize objects directly into strings without the need of a FileStream
object or any stream object, the StringReader
and StringWriter
classes will come in handy. Assume you want to serialize a List of integers, you may do the serialization and deserialization as this:
[C#]
public static string DataSerialize(List<int> myList)
{
StringWriter sw = new StringWriter();
XmlSerializer s = new XmlSerializer(myList.GetType());
s.Serialize(sw, myList);
return sw.ToString();
}
public static List<int> DataDeserialize(string data)
{
XmlSerializer xs = new XmlSerializer(typeof(List<int>));
List<int> newList = (List<int>)xs.Deserialize(new StringReader(data));
return newList;
}
[VB.NET]
Public Shared Function DataSerialize(ByVal myList As List(Of int)) As String
Dim sw As StringWriter = New StringWriter()
Dim s As New XmlSerializer(myList.GetType())
s.Serialize(sw, myList)
Return sw.ToString()
End Function
Public Shared Function DataDeserialize(ByVal data As String) As List(Of int)
Dim xs As New XmlSerializer(GetType(List(Of int)))
Dim newList As List(Of int) = CType(xs.Deserialize(New StringReader(data)), List(Of int))
Return newList
End Function