TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# StreamReader ReadLine, ReadLineAsync Examples

Use the StreamReader ReadLine method and the List. Get a List from a file.
ReadLine, ReadLineAsync. ReadLine is a StreamReader method. It returns the next text line from the file. We can process each line separately as it is encountered.StreamReaderFile
With ReadLineAsync, we can read lines in an asynchronous method—one that returns immediately, before the file is read. We can do other processing while the file is read.
An example. To start, ReadLine works well with the List collection. We have to first create a List, and then we add the "using" statement to begin our usage of the StreamReader.List

Using: For StreamReader, we use the "using" keyword to read the lines. This provides automatic disposal, releasing important resources.

Using

String: We store the ReadLine result in a string local. This will be null if we are done reading the file.

List: We call Add on the instance of List here. This appends another string to the List.

List Add

Finally: We display the results to the console with Console.WriteLine. We see all the lines in the file.

Console
C# program that uses ReadLine and List using System; using System.Collections.Generic; using System.IO; class Program { static void Main() { // Change this to point to a real file. const string fileName = @"C:\programs\file.txt"; // Create new List. List<string> lines = new List<string>(); // Use using-keyword for disposing. using (StreamReader reader = new StreamReader(fileName)) { // Use while not null pattern in while loop. string line; while ((line = reader.ReadLine()) != null) { // Insert logic here. // ... The "line" variable is a line in the file. // ... Add it to our List. lines.Add(line); } } // Print out all the lines in the list. foreach (string value in lines) { Console.WriteLine(value); } } } Contents,[file.txt]: Hello my friend Welcome to the Internet Third line in file Output Hello my friend Welcome to the Internet Third line in file
ReadLineAsync. We can use ReadLineAsync in a method that is marked as async. This means the method can execute while other code is still executing (after it is called, before it returns).

So: The async method is non-blocking. We can still process each line in the file as we encounter it.

Tip: Async code can be a huge benefit when the file is slow to be read, and other processing must occur.

Important: We must use the await and async keywords, and the Task class for any return values (if needed).

asyncStreamReader ReadToEndAsync
C# program that uses ReadLineAsync using System; using System.IO; using System.Threading.Tasks; class Program { const string _file = @"C:\programs\huge-file"; public static void Main() { // For testing. CreateHugeFile(); // We can run code in Main() without stopping for all the ReadLine calls in CountLinesAsync. Console.WriteLine("In main method (1)"); Task<int> task = CountLinesAsync(); // This next statement is reached immediately, before the file is read. Console.WriteLine("In main method (2)"); task.Wait(); Console.WriteLine("Result (3): " + task.Result); } static void CreateHugeFile() { using (StreamWriter writer = new StreamWriter(_file)) { for (int i = 0; i < 10000; i++) { writer.WriteLine("Huge file line"); } } } static async Task<int> CountLinesAsync() { int count = 0; using (StreamReader reader = new StreamReader(_file)) { while (true) { string line = await reader.ReadLineAsync(); if (line == null) { break; } count++; } } Console.WriteLine("At end of CountLinesAsync"); return count; } } Output In main method (1) In main method (2) At end of CountLinesAsync Result (3): 10000
IOException. You will want to catch IOException if your application's stability is critical. You could catch all IO exceptions and return an empty array if the file cannot be read.IOExceptionCatch
A discussion. This code gives you a chance to test each line, as with a regular expression, before adding it. You could use File.ReadAllLines, but you can't test each line first that way.Regex

Arrays: When you have added all the correct lines to the List, you can convert the List to an array, as with ToArray().

Convert List, ArrayToArray

Note: If you need a complete array of lines from a file, you can use the static File.ReadAllLines method.

File.ReadAllLines
A summary. We read each line into a file line-by-line. This can provide superior memory management over allocating an entire array. We can test each line before storing it.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf