将流转换为字节串

Converting Stream to ByteString

我有 Stream,我需要 return 通过 protobuf 消息作为 bytes。如何将 Stream 转换为 protobuf 期望的 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 中的 C# 编译器一直显示此错误消息:

Cannot implicitly convert type '' to 'Google.Protobuf.ByteString'.

我知道我遗漏了一些东西并且我缺乏 Streamsprotocol buffers 的知识。

实际上,我可能已经回答了我自己的问题。 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;
}

如果有人发现这有什么问题,请随时告诉我!谢谢!

我使用 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();
   }
}

但是,接下来我必须将 Bytearray 更改为 Protobuf3[=17 的 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

仅此而已。你在两边都有完全相同的字节。