如何在 C# 中将 BinaryReader 转换为 Stream?

发布于 2024-12-10 11:04:22 字数 155 浏览 1 评论 0 原文

我必须完整读取“.bin”文件并将流传递给函数。我用 BinaryReader 尝试过,它可以很好地逐字节读取值,我想将整个文件作为字符串流传递给我的函数。 StreamReader 的使用给出了垃圾信息,看起来 StreamReader 无法正确读取 bin 文件。

提前致谢。

I have to read a ".bin" file fully and pass the stream to a function. I tried it with BinaryReader which worked fine for reading values byte by byte, I want to pass the whole file as a string stream to my function. Usage of StreamReader gives garbage information, it looks like StreamReader can't read a bin file properly.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

提笔落墨 2024-12-17 11:04:22

不要将二进制数据作为字符串传递。相反,请使用与您可能从中读取它的任何Stream分离的byte[]StreamReader 用于读取文本是正确的,因此您需要使用 BinaryReader 或只是 直接使用Stream.Read()方法。如果您正在读取的流允许搜索(通过 CanSeek 属性),您可以发现它的Length 并一次性从流中读取所有字节。

但是,如果流非常大或不支持查找,则在读取时需要更加精细,分块进行,直到 Read() 方法返回 0< /code> (这意味着已到达流末尾)。

没有 StreamReader.ReadToEnd() 相当于读取二进制数据,但将其定义为扩展方法并不是很困难。

Don't pass binary data around as a string. Instead, use byte[] which is detached from any Stream you might have read it from. It's correct that StreamReader is for reading text, so you need to use BinaryReader or just the Stream.Read() method directly. If the stream you're reading from allows seeking (exposed through the CanSeek property), you can discover its Length and read all bytes from the stream in one go.

If, however, the stream is very large or doesn't support seeking, you need to be a bit more elaborate when reading by doing it in chunks until the Read() method returns 0 (which means the end of the stream has been reached).

There is no StreamReader.ReadToEnd() equivalent for reading binary data, but defining one as an extension method isn't very hard.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文