C# 将字节添加到文件开头?
在文件开头添加字节的最快且最有效的方法是什么?基本上,我想打开一个文件,然后向其中添加一些字节。我想过使用循环,但考虑到要添加的所有字节都是相同的,我认为没有必要。
What is the fastest and most efficient way to prepend bytes at the beginning of a file? Basically, I want to open a file and then add a number of bytes to it. I thought of using a loop, but given that all of the bytes to prepend are the same, I don't think it would be necessary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种对于文件而言非原子的方法(也就是说,如果程序中途终止,数据可能会处于不一致的状态):
ReadBytes
),而不是一次一个字节 - 请参阅在流之间复制的最佳方式作为示例。然而,这种方法也可能会受到文件系统预读方案混乱的影响,并且需要查找/随机文件访问。由于这些问题,如果设备上的空间绝对有限,我只能诚实地推荐它。
另一种方法是原子文件(如果程序在任何阶段终止,则不会丢失数据,并且可以恢复进程):
ReadBytes
) - 在本例中为先前链接的所以问题应该“按原样工作”。“缺点”是它需要临时文件。
快乐编码。
One approach that is not atomic wrt the file (that is, if the program dies in middle the data could be left in an inconsistent state):
ReadBytes
), not a byte at a time - see best way to copy between streams for an example.This approach may also suffer from confusing the filesystem read-ahead scheme, however, and requires seeking / random file access. Because of these issues, I can only honestly recommend it if space on the device is an absolute premium.
Another approach that is atomic wrt the file (if the program dies any stage no data is lost and the process can be recovered):
ReadBytes
) - in this case the previously linked SO question should "just work as it is".The "downside" is that it requires a temporary file.
Happy coding.
这是我个人能想到的最简洁的方法,但并不能避免像你想要的那样的循环:
它也可以使用一些错误处理,但你明白了。
This is about the most succinct way I could personally think of, but doesn't avoid loops like you wanted:
It could also use some error handling, but you get the idea.
如果您确实需要前置,最“安全”的方法通常是将字节写入新文件,将旧文件写入新文件,最后交换文件(例如使用
File.Replace< /code> 并使用 null 作为目标备份文件名。)。请注意,您需要足够的空间来复制旧文件!
If you truly need to prepend, the most "secure" way is normally to write to a new file your bytes, write to this new file the old file and in the end swap the files (using for example
File.Replace
and using null as destinationBackupFileName.). Be aware that you'll need enough space to copy the old file!我能想到的最简单的方法是创建一个字节数组,添加“前置”字节,然后将您想要使用的文件转换为另一个字节数组并将它们合并在一起!
The easiest way I could think of doing it would be to create a byte array, add in your "prepend" bytes and then convert the file you are wanting to use into another byte array and merge them together!