c# - 如何使用 protobuf 反序列化流并将其写入文件

标签 c# .net-4.5 protobuf-net

我需要记录对文件的裸 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

如果流不可查找,则在执行其他操作之前将其复制到内存流

然后使用

stream.Seek(0, SeekOrigin.Begin);

关于c# - 如何使用 protobuf 反序列化流并将其写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21731262/

相关文章:

c# - protobuf-net v2 r450继承

C# 单元测试异步错误

c# - 部分 MonthCalendar 本地化失败 ('Today' 标签未翻译)

c# - .NET 4.5 UserPrincipal.FindByIdentity (System.DirectoryServices.AccountManagement) 中的错误

c# - Protobuf-net序列化/反序列化

c# - 使用 ProtoBuf-net 快速获取序列化数据长度的方法?

c# - 无法从 .NET Core 2 控制台应用程序中的 config.json 读取数据

c# - 如何减慢申请速度?

c# - Umlaute 的文化感知字符串比较

wif - 尝试将 WIF 4.0 自定义 STS(来自项目模板)转换为使用 .NET 4.5