18

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!

2
  • 2
    Have you tried byte[] fileC = File.ReadAllBytes(dialog.FileName);
    – Todd Moses
    Commented Sep 12, 2012 at 4:05
  • @Todd Moses I already have the file as a byte[], I'm trying to read the text from that byte[] now. It's being given to me, and I don't have a file actually saved on the disk, and I do not want to have to save it to the disk and then read.
    – Kyle
    Commented Sep 12, 2012 at 4:30

2 Answers 2

39

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();
1
9

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.

2
  • 1
    I wonder why this answer doesn't have more upvotes. There might be a really strong reason to prefer using a 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
  • Nope, I think we all just went there because of the way the question was phrased. If OP hadn't used the word "file" we'd likely have had an answer like this one years sooner. The mind is a funny thing. Commented Mar 12, 2019 at 18:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.