我需要将一个裸的protobuf响应记录到一个文件中,并将其反序列化为一个对象。它只是让我做一个或另一个。下面的代码导致正确反序列化的对象,但也导致空白文本文件。我该怎么办呢?
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);
}
答案 0 :(得分:2)
您需要在反序列化和写入文件
之间将流重新设置为0如果流不可搜索,则在执行任何其他操作之前将其复制到内存流
然后使用
stream.Seek(0, SeekOrigin.Begin);
答案 1 :(得分:0)
如果流只能读取一次,你可以采取的另一种方法是使用输入和输出流的自定义Stream
装饰器,即
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
}