I have a text file in the form of a byte[].
I cannot save the file anywhere.
I would like to read all lines/text from this 'file'.
Can anyone point me in the right direction on how I can read all the text from a byte[] in C#?
Thanks!
ReadAllBytes() Method in C# with Examples. File. ReadAllBytes(String) is an inbuilt File class method that is used to open a specified or created binary file and then reads the contents of the file into a byte array and then closes the file.
Inside the io/ioutil package, there's a function called ReadFile() which is used to open a file and then convert its contents into a slice of bytes, and if for some reason, it isn't able to do so, then it will return an error too. Here is the syntax of the ReadLine() function.
C# is a strongly typed language. That means that every object you create or use in a C# program must have a specific type. Byte is an immutable value type that represents unsigned integers with values that range from 0 to 255 .
I would create a MemoryStream
and instantiate a StreamReader
with that, i.e:
var stream = new StreamReader(new MemoryStream(byteArray));
Then get the text a line at a time with:
stream.readLine();
Or the full file using:
stream.readToEnd();
Another possible solution using Encoding
:
Encoding.Default.GetString(byteArray);
It can optionally be split to get the lines:
Encoding.Default.GetString(byteArray).Split('\n');
You can also select a particular encoding like UTF-8 instead of using Default
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With