Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Stream to ByteString

I have Stream that I need to return through a protobuf message as bytes. How do I convert the Stream into the ByteString that is expected by protobuf? Is it as simple as it appears in the documentation Serialization?

Due to the nature of the project I'm unable to test it well so I'm kinda working blind. Here is what I'm working with:

Protocol buffer:

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;
}

I have attempted to convert the Stream to a string or a byte[] but C# compiler in VS keeps showing this error message:

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

I know I am missing something and my knowledge of Streams and protocol buffers is lacking.

like image 853
koshi Avatar asked Mar 21 '19 14:03

koshi


Video Answer


1 Answers

Actually, I may have answered my own question. ByteString has an extension that accepts a 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;
}

If anyone sees something wrong with this feel free to let me know! Thanks!

like image 94
koshi Avatar answered Sep 20 '22 21:09

koshi