Iris Classon
- CATALOG -
Iris Classon - In Love with Code

Serializing and deserializing (packing/unpacking) to a file and/or memorystream with MessagePack in C#

Using MessagePack in C#

In RE to the last post: Stupid Question 106: What is MessagePack?

Here is just some playground code (I just wanted to write and read from a text file using MessagePack). Seems to be working rather nice :) Not the prettiest code, I just wanted to whip something together in a few minutes, took me maybe 15 min for this example.

To use MessagePack for beginners with C#:

  1. Go to Github and download MessagePack
  2. Unzip
  3. Open the project and build it
  4. Create your project and reference the DLL(s) in the MessagePack project

Serializing and deserializing (packing/unpacking) to a file and/or memorystream with MessagePack in C#

[sourcecode language="csharp”]
using System.IO;
using MsgPack.Serialization;

namespace MsgPack
{
class Program
{
static void Main(string[] args)
{
CreateMsgPack();
}

    static void CreateMsgPack()  
    {  
        WriteToFile();  
        ReadFromFile();  

        using (var stream = new MemoryStream())  
        {  
            var serializer = MessagePackSerializer.Create<Person>();  
            serializer.Pack(stream, CreateIris());  
            stream.Position = 0;  
            var person = serializer.Unpack(stream);  
        }  
    }  

    static void WriteToFile()  
    {  
        var serializer = MessagePackSerializer.Create<Person>();  

        using(Stream stream = File.Open(@"C:\Users\Iris\msg.txt", FileMode.Create))  
        {  
            serializer.Pack(stream, CreateIris());  
        }  
    }  

    static void ReadFromFile()  
    {  
        var serializer = MessagePackSerializer.Create<Person>();  

        using (Stream stream = File.Open(@"C:\Users\Iris\msg.txt", FileMode.Open))  
        {  
            var iris = serializer.Unpack(stream);  
        }  
    }  

    static Person CreateIris()  
    {  
        return new Person  
                   {  
                       Age = 28,  
                       Name = "Iris Classon",  
                       FavoriteNumbers = new[] {2,3,4}  
                   };  
    }  

}  

public class Person  
{  
    public string Name { get; set; }  
    public int Age { get; set; }  
    public int[] FavoriteNumbers { get; set; }  
}  

}

[/sourcecode]

Comments

Leave a comment (via email)
Kim Johansson
12/22/2012 4:45:41 PM
I need to check this out, might be just what I need for my event sourcing storage.

In case you didn't know, there's a Nuget package for MessagePack. (http://nuget.org/packages/MsgPack)

Continue with the great posts! 


Last modified on 2012-12-17