C#: Reading lines from a file

Robson William
2 min readOct 2, 2020

The “Quest” app is evolving, slowly but steady. And in this post I am going to share the things I have been learning regarding the manipulation of lines from files in C#.

Getting a list of lines

To be able to manipulated the lines of a file, I am using the “ReadAllLines” method from the File class, which is in the System.IO namespace. Here is an example of how I am using it:

As the C# documentation describes, the “ReadAllLines” method:

Opens a text file, reads all lines of the file into a string array, and then closes the file.

In my example above I call the “ToList” method to convert the string array into a List of strings. The List<string> has some convenient methods such as “Remove”, which I use to delete a line.

It is also important to understand what defines a line. The C# documentation also explains what is considered a line by the ReadAllLines method:

A line is defined as a sequence of characters followed by a carriage return (‘\r’), a line feed (‘\n’), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.

What I like about this method is that, since it returns an enumerable object, I can use the “foreach” loop to iterate over the list. Quest uses the “Find” method on the List<string> to search for a line that contains the string provided by the user to delete a “todo” or mark it as complete.

--

--

Robson William

Software developer. C# and Go. Enthusiast for gRPC and IoT. Also husband, father and believer in Christ. https://robwillup.com