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#:
- Go to Github and download MessagePack
- Unzip
- Open the project and build it
- 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
Kim Johansson
Last modified on 2012-12-17