19

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); 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. Commented Sep 12, 2012 at 4:30

2 Answers 2

41

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();
Sign up to request clarification or add additional context in comments.

1 Comment

No problem, I had to figure that out for a super important reason once.
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 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.