Search code examples
c#serializationprotobuf-net.net-6.0

How to fix Invalid wire-type issue in c# protobuf-net


I was converting a protobuf-net deserialize call from a generic call to specifying the type.

using var memStream = new MemoryStream(bytes);
var result = Serializer.Deserialize<T>(memStream);

To

using var memStream = new MemoryStream(bytes);
var result = Serializer.Deserialize(memStream, type);

And I get an exception

ProtoBuf.ProtoException: Invalid wire-type (Fixed64); this usually means you have over-written a file without truncating or setting the length; see https://stackoverflow.com/q/2152978/23354
   at ProtoBuf.ProtoReader.State.ThrowProtoException(String message) in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 764
   at ProtoBuf.ProtoReader.State.ThrowWireTypeException() in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 758
   at ProtoBuf.Internal.PrimaryTypeProvider.ProtoBuf.Serializers.ISerializer<System.Type>.Read(State& state, Type value) in /_/src/protobuf-net.Core/Internal/PrimaryTypeProvider.Primitives.cs:line 292
   at ProtoBuf.ProtoReader.State.<ReadAsRoot>g__ReadFieldOne|102_0[T](State& state, SerializerFeatures features, T value, ISerializer`1 serializer) in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 1075
   at ProtoBuf.ProtoReader.State.ReadAsRoot[T](T value, ISerializer`1 serializer) in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 1059
   at ProtoBuf.ProtoReader.State.DeserializeRoot[T](T value, ISerializer`1 serializer) in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 1036
   at ProtoBuf.Serializer.Deserialize[T](Stream source, T value, Object userState, Int64 length) in /_/src/protobuf-net/Serializer.Deserialize.cs:line 43
   at Computer.Bus.Integration.ProtoSerializer.Deserialize(Byte[] bytes, Type type) in C:\Users\squir\source\repos\Computer.Bus\source\Computer.Bus.Integration\ProtoSerializer.cs:line 21
   at Computer.Bus.RabbitMq.Client.BusClient.<>c__DisplayClass6_0.<<Subscribe>g__innerCallback|0>d.MoveNext() in C:\Users\squir\source\repos\Computer.Bus\source\Computer.Bus.RabbitMq\Client\BusClient.cs:line 52

All my attempts to find a solution usually have to do with serialization errors or byte management. This is a simple app. I am trying to (de)serialize a simple type declared within the same source.

[ProtoContract]
public record ProtoModel
{
    [ProtoMember(1)] 
    public double fNumber { get; init; } = DateTime.Now.ToBinary();

    [ProtoMember(2)] 
    public string someString { get; init; } = "something";
    [ProtoMember(3)]
    public DateTime Timestamp { get; init; } = DateTime.Now;
}

Solution

  • After I did some digging, I found out that I had put the parameters in the wrong order. Deserialization should look like this

    using var memStream = new MemoryStream(bytes);
    var result = Serializer.Deserialize(type, memStream);