Google Protocol Buffers - serialize to byte array

Roka545 picture Roka545 · Jan 19, 2017 · Viewed 16.8k times · Source

I'm following the tutorial for using Google Protocol Buffers for C#. I don't see an example for converting an object into a byte array - does anyone know how to do that? I've auto-generated a FilePath classes using the protoc compiler and have this so far:

FilePath fp = new FilePath
{
    Path = "TestPath",
    RealTimeMultiple = 5.0f
};

So, I need to know how to properly serialize the fp object without the use of BinaryFormatter.

Answer

Jon Skeet picture Jon Skeet · Jan 19, 2017

Assuming you're using the Google.Protobuf nuget package, you can just use:

using Google.Protobuf;

...

byte[] bytes = fp.ToByteArray();

You need the using directive for Google.Protobuf to make the IMessage.ToByteArray extension method available - that may be what you were missing before.