kos*_*shi 5 .net c# protocol-buffers proto grpc
我有Stream我需要通过 protobuf 消息作为bytes. 如何将 转换Stream为ByteStringprotobuf 所期望的?它是否像文档序列化中显示的那样简单?
由于项目的性质,我无法很好地测试它,所以我有点盲目工作。这是我正在使用的内容:
协议缓冲区:
message ProtoResponse {
bytes ResponseValue = 1;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我试图将 转换Stream为 astring或 abyte[]但 VS 中的 C# 编译器不断显示此错误消息:
Cannot implicitly convert type '' to 'Google.Protobuf.ByteString'.
我知道我错过了一些东西,我的知识Streams和protocol 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;
}
Run Code Online (Sandbox Code Playgroud)
如果有人发现这有什么问题,请随时告诉我!谢谢!