Wednesday, October 28, 2009

Streams and Serialization

I started working on Streams and Serialization. I've worked with both of these concepts in-depth in Java (and have worked with System.IO Namespace in .NET), so this was an enjoyable area of study.

The biggest challenge was just remembering the class names, and not getting them mixed up with Java.

Here is a small test program I wrote that uses Binary Serialization and File Streams.

It serializes a strongly-typed list of IDs to a binary file, and deserializes it back. I had concerns about casting on formatter.Deserialize(stream), but it appeared to work okay. I do think that this is a dangerous practice, though, but am not sure of a better way to do it in a typesafe manner.


using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Serialization
{
class Program
{
static void Main(string[] args)
{
String serializedFilePath = @"c:\myObject.bin";
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
IList<int> myIds = new List<int> { 10, 20, 30, 40, 50, 60, 70, 80, 90, 99 };
FileStream fs = new FileStream(serializedFilePath, FileMode.Create, FileAccess.ReadWrite);

try
{
Console.WriteLine("About to serialize");
formatter.Serialize(ms, myIds);
formatter.Serialize(fs, myIds);

}
finally
{
ms.Close();
fs.Close();
}

// Now, we will deserialize from the file
try
{
Console.WriteLine("About to deserialize");
fs = new FileStream(serializedFilePath, FileMode.Open, FileAccess.Read);
IList<int> deserializedIds = (IList<int>) formatter.Deserialize(fs);

StringBuilder sBuilder = new StringBuilder();
foreach (int id in deserializedIds)
{
sBuilder.Append(" ");
sBuilder.Append(id);
}
Console.WriteLine("Deserialized List: " + sBuilder.ToString());
}
finally
{
fs.Close();
}
Console.ReadKey();
}
}
}

No comments:

Post a Comment