How do you read binary data in C# .NET and then convert it to a string?
As opposed to using StreamReader/Filestream
I want to read binary data开发者_开发问答 from files and show that data (formatted) in a textbox.
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;
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.
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.
精彩评论