Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read all text from a byte[] file?

Tags:

c#

bytearray

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!

like image 391
Kyle Avatar asked Sep 12 '12 04:09

Kyle


People also ask

How to read byte array from file in c#?

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.

How do I read a string from a file in Golang?

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.

What is a byte in a text file?

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 .


2 Answers

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();
like image 68
Kevin Stricker Avatar answered Oct 07 '22 21:10

Kevin Stricker


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.

like image 29
bklaric Avatar answered Oct 07 '22 23:10

bklaric