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?
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.
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.
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);
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
...
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()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With