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

Unlike using StreamReader/Filestream , I want to read binary data from files and show that data (formatted) in a text box.

+4
source share
3 answers

There are different cases when you need to read a binary file, as it is not clear what you are really trying to achieve here:

  • read an arbitrary file and display it as a series of hexadecimal values ​​(similar to representing a binary file in Visual Studio or any other binary file viewer). Answer Jeff M. Answer that.
  • Reading and writing your own objects using binary serialization. Check serialization on MSDN - http://msdn.microsoft.com/en-us/library/et91as27.aspx and read on the BinaryFormatter objects.
  • Read elses binary format (e.g. JPEG, PNG, ZIP, PDF). In this case, you need to know the file structure (you can often find documentation on the file format) and use BinaryReader to read individual fragments of the file. For most common file formats, it’s easy to find existing libraries that can read such files in a more convenient way. The MSDN article on BinaryReader also has a basic usage example: http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx .
+4
source

So, binary data like in potentially non-printable data? Well, if you want to print the data as a sixth line, take the data as an array of bytes, and then convert it to a hexadecimal 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; 
+7
source

Use BinaryReader to read the file. Then encode the byte array that is read from the file in base64 format, and assign a base64 encoded string in the text box

UPDATE:

A byte array that reads from a file can be encoded in a different text encoding before assigning a text field to display. Take a look at the following namespaces in the .net class, which are related to the character encoding format:

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

Please make sure you know the exact encoding of the target file before converting from a byte array to an encoded string. Or you can check the bytes of the BOM file.

UPDATE (2):

Note that it is not possible to convert a non-text file (for example, an image file, a music file) using any of the System.Text classes. Otherwise, the value will not be displayed for the text box.

+3
source

Source: https://habr.com/ru/post/1345489/


All Articles