Reputation: 661
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);
}
Upvotes: 2
Views: 1836
Reputation: 1062865
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
}
Upvotes: 0
Reputation: 9975
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);
Upvotes: 2