When I run my program and open a file it prints the following text in the console:
File opened successfully
System.Linq.Enumerable+<TakeIterator>d__25`1[System.Byte]
The first line is correct, but the second line is the one I don't understand. What's intended to happen is that it's supposed to read the first 4 bytes of the file and turn it into a string to print to the console so I can see that it reads the file header correctly. The expected output in this situation would be "MThd", which is the file type identifier.
Here is the code I have for creating the string:
if(fileName != null)
{
byte[] fileBytes = File.ReadAllBytes(fileName);
string header = fileBytes.Take(4).ToString();
Console.WriteLine(header);
}
If you expect a text file, use ReadAllText
instead of ReadAllBytes
. If you want to read a stream of bytes and interpret that as a string, use the appropriate decoding method, for example
var header = System.Text.UTF8Encoding.UTF8.GetString(fileBytes.Take(4));
With today's multi-byte character sets, it is no longer guaranteed that a certain number of bytes corresponds to a certain number of characters. This is only reliable if you can stick to the ASCII encoding.
var header = System.Text.ASCIIEncoding.ASCII.GetString(fileBytes.Take(4));
byte[].Take() seems to return something of type
System.Linq.Enumerable+<TakeIterator>d__25``1[System.Byte]
which looks like cannot be converted to a string directly.
Try iterating through it and writing (strings) of its components to the console instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.