将流覆盖到ByteString

时间:2019-03-21 14:52:52

标签: c# protocol-buffers proto

我有Stream,我需要通过protobuf消息返回为bytes。如何将Stream转换为预期的ByteString?它是否像文档Serialization中所示的那样简单。由于项目的性质,我无法对其进行良好的测试,因此我有点盲目工作。 这是我正在使用的东西:

协议缓冲区:

message ProtoResponse{
   bytes ResponseValue = 1;
}

C#

public ProtoResponse SendResponse(Stream stream)
{
   var response = ProtoResponse
      {
         // this obviously does not work but 
         // but it conveys the idea of what I am going for
         ResponseValue = stream
      }
   return response;
}

我试图将Stream转换为stringbyte[],但是VS不断抛出相同的错误Cannot implicitly convert type '' to 'Google.Protobuf.ByteString'。我知道我丢失了某些东西,并且缺乏对Streamsprotocol buffers的了解。

2 个答案:

答案 0 :(得分:0)

实际上,我可能已经回答了我自己的问题。 ByteString的扩展名可以接受byte[]

public ProtoResponse SendResponse(Stream stream)
{
   byte[] b;
   using (var memoryStream = new MemoryStream())
   {
      stream.CopyTo(memoryStream);
      b = memoryStream.ToArray();
   }
   var response = ProtoResponse
      {
         ResponseValue = ByteString.CopyFrom(b)
      }
   return response;
}

如果有人发现任何问题,请随时告诉我!谢谢!

答案 1 :(得分:0)

我使用C#,而Protobuf syntax = 3;GRPC一起使用。就我而言,它看起来像这样:

我找到了将Image更改为ByteArray的方法,此示例用于了解我的响应的下一部分。

private static byte[] ImageToByteArray(Bitmap image)
{
  using (var ms = new MemoryStream())
   {
     image.Save(ms, image.RawFormat);
     return ms.ToArray();
   }
}

但是,接下来我必须将 Protobuf3

Bytearray 更改为 ByteString
byte[] img = ImageToByteArray(); //its method you can see above
ByteString bytestring;
 using (var str = new MemoryStream(img))
 {
    bytestring = ByteString.FromStream(str);
 }

您可以简单地使用ByteString.FromStream(MemoryStream),而无需使用CopyFrom方法。

如果我们查看此消息的接收者,他需要将 ByteString 更改为 ByteArray ,例如保存照片:

byte[] img = request.Image.ToByteArray(); //this is received message

仅此而已。双方的字节数完全相同。