TheDeveloperBlog.com

Home | Contact Us

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

C# ReadLine Reads File Into List

This C# example program uses the StreamReader ReadLine method and the List type.

ReadLine is a StreamReader method.

It returns the next text line from the file. By processing each line separately, we can apply logic to test the lines for validity or reject them. This avoids unnecessary complexity.

StreamReader

Example. First we look at the ReadLine method on StreamReader and how you can use it with List. The .NET Framework doesn't provide a "Read All Lines" method on StreamReader, but our solution will fill that need.

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

File.ReadAllLines

C# program that uses ReadLine and List

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
	const string f = "TextFile1.txt";

	// 1
	// Declare new List.
	List<string> lines = new List<string>();

	// 2
	// Use using StreamReader for disposing.
	using (StreamReader r = new StreamReader(f))
	{
	    // 3
	    // Use while != null pattern for loop
	    string line;
	    while ((line = r.ReadLine()) != null)
	    {
		// 4
		// Insert logic here.
		// ...
		// "line" is a line in the file. Add it to our List.
		lines.Add(line);
	    }
	}

	// 5
	// Print out all the lines.
	foreach (string s in lines)
	{
	    Console.WriteLine(s);
	}
    }
}

Output
    (Prints contents of TextFile1.txt)

This is a text file I created,
Just for this article.

In this example, we use List, which is a generic object that expands to fit your data. The List data structure will easily accommodate files from 0 to 1,000,000+ lines long. It is perfect in this program context.

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

Using

Next, the syntax for ReadLine is complicated. We first assign the string to the ReadLine result string. That string will be null if we are done reading the file. We need a Boolean result for an if-statement, so we test against null.

IfNull

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

List Add Method

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

Console.WriteLine

Note: This can catch some really simple bugs, such as those caused by an invalid filename.

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. You may have more detailed requirements, but IOException works well.

IOExceptionCatch

Discussion. This code gives you a chance to test each line, as with a regular expression, before adding it to the array. You could use File.ReadAllLines to consume the file into an array, but you can't test each line first that way.

Regex.Match

Using arrays instead. When you are done with the testing of the file line-by-line with ReadLine, and have added all the correct lines to the List, you can convert the List to an array, as with ToArray().

Convert List to ArrayToArray

Summary. We saw here a common approach of reading each line into a file line-by-line. This can provide superior memory management over allocating an entire array. It offers an opportunity for you to test each line before storing it.


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