如何读取 C# .NET 中的二进制数据,然后将其转换为字符串?
与使用 StreamReader/Filestream 相反,我想从文件中读取二进制数据并在文本框中显示该数据(格式化)。
As opposed to using StreamReader/Filestream
I want to read binary data from files and show that data (formatted) in a textbox.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么二进制数据就像潜在的不可打印数据一样吗?如果您想将数据打印为十六进制字符串,请将数据作为字节数组,然后转换为十六进制表示形式。
So binary data as in potentially non-printable data? Well if you want to print the data out as a hex string, take the data as an array of bytes then convert to a hex representation.
当需要读取二进制文件时,存在不同的情况,因为不清楚您真正想要实现的目标是:
There are different cases when one need to read binary file, since it is unclear what you really trying to achieve here are some:
使用 BinaryReader 读取文件。然后以 Base64 格式对从文件读取的字节数组进行编码,并在文本框中分配 Base64 编码的字符串
更新:
从文件读取的字节数组可以在分配给文本框进行显示之前以各种文本编码进行编码。查看 .net 类中与字符编码格式相关的以下命名空间:
请确保您知道确切的编码在进行从字节数组到编码字符串的任何转换之前,先检查目标文件。或者您可以检查该文件 BOM 字节。
更新(2):
请注意,您无法使用任何System.Text 类转换非文本文件(例如图像文件、音乐文件)。否则,在文本框中显示对您来说是没有意义的。
Use BinaryReader to read the file. Then encode the byte array that read from file in base64 format and assign the base64 encoded string in the textbox
UPDATE:
The byte array that read from file can be encoded in various text encoding before assigning to textbox for display. Take a look at following namespaces in .net class that related to characters encoding format:
Please ensure that you know the exact encoding of the target file before making any conversion from byte array to encoded string. Or you can check that file BOM bytes.
UPDATE (2):
Please note that you can't convert non-text file (eg image file, music file) using any of System.Text class. Otherwise it is meaning-less for you to display in the textbox.