How do you read binary data in C# .NET and then convert it to a string?

。_饼干妹妹 提交于 2019-12-12 12:27:22

问题


As opposed to using StreamReader/Filestream I want to read binary data from files and show that data (formatted) in a textbox.


回答1:


There are different cases when one need to read binary file, since it is unclear what you really trying to achieve here are some:

  • read random file and display as series of hex values (similar to binary file view in Visual Studio or any other binary file viewer). Berfectly covered by Jeff M's answer.
  • Reading and writing your own objects using binary serialization. Check serialization walkthrough on MSDN - http://msdn.microsoft.com/en-us/library/et91as27.aspx and read on BinaryFormatter objects.
  • Reading someone elses binary format (like JPEG, PNG, ZIP, PDF). In this case you need to know structure of the file (you can often find file format documentation) and use BinaryReader to read individual chunks of the file. For most of the common file formats it is easy to find existing libraries that allow reading such files in more convinient way. MSDN article on BinaryReader have basic usage sample also: http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx.



回答2:


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.

string path = @"path\to\my\file";
byte[] data = File.ReadAllBytes(path);
string dataString = String.Concat(data.Select(b => b.ToString("x2")));
textBox.Text = dataString;



回答3:


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:

  • System.Text.ASCIIEncoding
  • System.Text.UTF8Encoding
  • System.Text.UnicodeEncoding
  • System.Text.UTF32Encoding
  • System.Text.UTF7Encoding

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.



来源:https://stackoverflow.com/questions/5454182/how-do-you-read-binary-data-in-c-sharp-net-and-then-convert-it-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!