Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReadAllLines for a Stream object?

Tags:

c#

file

text

stream

There exists a File.ReadAllLines but not a Stream.ReadAllLines.

using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Test_Resources.Resources.Accounts.txt")) using (StreamReader reader = new StreamReader(stream)) {     // Would prefer string[] result = reader.ReadAllLines();     string result = reader.ReadToEnd(); } 

Does there exist a way to do this or do I have to manually loop through the file line by line?

like image 579
Ryan Peschel Avatar asked Nov 09 '12 17:11

Ryan Peschel


People also ask

How to Read file to Stream c#?

First create FileStream to open a file for reading. Then call FileStream. Read in a loop until the whole file is read. Finally close the stream.

What is the difference between ReadAllLines and ReadAllText in C#?

ReadAllLines returns an array of strings. Each string contains a single line of the file. ReadAllText returns a single string containing all the lines of the file.

What is ReadAllLines C#?

ReadAllLines(String) is an inbuilt File class method that is used to open a text file then reads all lines of the file into a string array and then closes the file. Syntax: public static string[] ReadAllLines (string path);


2 Answers

You can write a method which reads line by line, like this:

public IEnumerable<string> ReadLines(Func<Stream> streamProvider,                                      Encoding encoding) {     using (var stream = streamProvider())     using (var reader = new StreamReader(stream, encoding))     {         string line;         while ((line = reader.ReadLine()) != null)         {             yield return line;         }     } } 

Then call it as:

var lines = ReadLines(() => Assembly.GetExecutingAssembly()                                     .GetManifestResourceStream(resourceName),                       Encoding.UTF8)                 .ToList(); 

The Func<> part is to cope when reading more than once, and to avoid leaving streams open unnecessarily. You could easily wrap that code up in a method, of course.

If you don't need it all in memory at once, you don't even need the ToList...

like image 73
Jon Skeet Avatar answered Oct 09 '22 23:10

Jon Skeet


The .EndOfStream property can be used in the loop instead of checking if the next line is not null.

List<string> lines = new List<string>();  using (StreamReader reader = new StreamReader("example.txt")) {     while(!reader.EndOfStream)     {         lines.Add(reader.ReadLine());     } } 
like image 42
Bryan Johnson Avatar answered Oct 09 '22 22:10

Bryan Johnson