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!
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!
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
.
StreamReader
and a MemoryStream
, but I don't know if that's true. Perhaps it's because the other answer is older. One small detail I appreciate about using Encoding
is that it's more apparent that you must either choose an encoding (UTF-8, etc.) or use the default.
Commented
Jan 10, 2019 at 16:45