2

I need to log a bare protobuf response to a file and deserialize it to an object as well. It is only letting me do one or the other. The code below results in a correctly deserialized object but also a blank text file. How can I work this?

try
{
    ProtoBuf.Serializer.Serialize(webRequest.GetRequestStream(), myclass);
}
finally
{
    webRequest.GetRequestStream().Close();
}
var webRequest = (HttpWebRequest)WebRequest.Create(EndPoint);
webRequest.Method = "POST";
WebResponse response = webRequest.GetResponse();
var responseStream = response.GetResponseStream();

//deserializing using the response stream
myotherclassinstance = ProtoBuf.Serializer.Deserialize<TidalTV.GoogleProtobuffer.BidResponse>(responseStream);

//trying and failing to copy the response stream to the filestream
using (var fileStream = File.Create(Directory.GetCurrentDirectory() + "\\ProtobufResponse"))
{
        responseStream.CopyTo(fileStream);
}
rcj
  • 631
  • 2
  • 11
  • 27

2 Answers2

2

You need to seek the stream back to 0 between deserializing and writing to file

If the stream isn't seekable then Copy it to a memory stream before doing anything else

Then use

stream.Seek(0, SeekOrigin.Begin);

James
  • 9,774
  • 5
  • 34
  • 58
  • Oh okay great. Yea It wouldn't let me call seek from the stream itself. Said wasn't invokable or whatever. – rcj Feb 12 '14 at 14:58
  • @rcj Not sure what type of stream HttpWebResponse returns, but I think you'd be best copying it to a memory stream first – James Feb 12 '14 at 15:02
  • `responseStream.CopyTo(responseMemoryStream)` results in a stream that seems empty. – rcj Feb 12 '14 at 15:25
  • To copy, I used `new MemoryStream(ReadFully(responseStream))` from http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream – rcj Feb 12 '14 at 15:51
0

Another approach you could take, if the stream can only be read once, is a custom Stream decorator that takes the input and output streams, i.e

 public class MimicStream : Stream
 {
    Stream readFrom, writeTo;
    //...
    public override int Read(byte[] buffer, int offset, int count)
    {
        int result = readFrom.Read(buffer, offset, count);
        if(result > 0)
        {
            writeTo.Write(buffer, offset, result);
        }
        return result;
    }
    // etc
 }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900