通过StreamWriter或文件写入修改数据?
我需要创建二进制数据文件。它无法一次性创建,我需要序列化一些数据,然后返回并在标头中写入偏移量。文件将适合内存(几兆字节)。我可以使用 BinaryWriter
并返回使用 writer.Seek(x, SeekOrigin.Begin)
写入偏移量吗?或者也许写入文件(然后修改它)有什么优点?或者也许没有真正的区别?
I need to create binary data file. It cannot be created in one pass, I need to serialize some data, then go back and write offsets in the header. File will comfortably fit in memory (a few megabytes). Can I use BinaryWriter
and go back to write offsets using writer.Seek(x, SeekOrigin.Begin)
? Or maybe writing to file (and then modyfing it) has any advantages? Or maybe there is no real difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该创建一个打包结构来表示标头,而不是偏移到文件中。填写结构并将其写入文件的开头。一次性阅读结构也会更容易。
Rather than offsets into the file, you should create a packed structure to represent the header. Fill in the structure and write it at the beginning of the file. It will also be easier to read the structure in one shot.
我想我理解你的问题。您正在序列化程序其他部分的对象,并且您不知道每个块有多大,直到您要求序列化它。并且您不想一次序列化所有对象,因为这可能是一个很多记忆。
因此,您想在文件的前面留出一些空间,以块的形式写入二进制数据,同时记录每个块的大小,然后返回并写入标头以指示每个块的开始和停止位置。
您要求的解决方案似乎是合理的,但我相信如果您返回标头位置,BinaryWriter 将会覆盖,因此您需要在前面编写一个空字节垫,以便为自己留出空间来编写标头 -
http://msdn.microsoft.com/en -us/library/system.io.binarywriter.seek.aspx#Y640
现在的问题是,你的标头有多大?你写了多少个空字节?可能取决于您必须序列化的对象的数量。听起来现在你遇到了和以前一样的问题。
相反,我会按顺序打包数据,例如:
长度参数编码该块的总长度,接下来您拥有每个块拥有的任何属性,然后是要序列化的实际对象的原始字节。
I think I understand your problem. You're serializing objects from other parts of your program, and you don't know how large each chunk is until you ask to serialize it.. and you don't want to serialize all of them all at once because that might be a lot of memory.
So you want to leave some room at the front of your file, write your binary data in chunks meanwhile recording how big each chunk was, then go back and write header to indicate where each chunk starts and stops.
The solution you're asking seems reasonable, but I believe BinaryWriter will overwrite if you seek back to your header location, so you'll need to write a pad of empty bytes up front to leave yourself room to write the header -
http://msdn.microsoft.com/en-us/library/system.io.binarywriter.seek.aspx#Y640
Now the problems, how big is your header going to be? How many empty bytes do you write? Probably going to depend on the number of objects you have to serialize. Sounds like now you have the same problem as before.
Instead, I would pack your data sequentially, as an example:
The length parameter encodes the total length of that chunk, next you have whatever properties you have per chunk, then whatever the raw bytes are for the actual object being serialized.