joi, 31 martie 2011

Serialize an array to XML in .NET Framework

Well, this is not too much of a big deal since with a little knowledge about Serialization you will be able to figure this out quite rapidly. I only thought of posting this here since I had in mind the issue of converting an array of (string) values into an XML format and then have it deserialized at a later time when I would have need the array again. For this purpose I used the XmlSerializer class and the MemoryStream class.
The example code I give below shows how to convert a string array to XML and then how to deserialize it from the XML format into a new array.

public static void SerializeDeserializeArray( )
    string[ ] strArr = new string[ ] {
        "C:\\Program Files\\myFile1.txt",
        "C:\\Program Files\\myFile2.txt",
        "C:\\Program Files\\myFile3.txt"

    MemoryStream memStream = new MemoryStream( );
    StreamWriter sw = new StreamWriter( memStream );

    XmlSerializer ser = new XmlSerializer( typeof( string[ ] ) );
    ser.Serialize( sw, strArr );

    StreamReader sr = new StreamReader( memStream );

    memStream.Position = 0;
    string str = sr.ReadToEnd( );

    memStream.Position = 0;
    string[ ] deserArr = (string[ ] )ser.Deserialize( memStream );

    if( deserArr != null )
        foreach( string s in deserArr )
            Console.WriteLine( s );

    Console.WriteLine( );

Niciun comentariu:

Trimiteți un comentariu