سؤال

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);
}
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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
 }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top