Home
C#
File.ReadAllLines, Get String Array
Updated May 26, 2021
Dot Net Perls
File.ReadAllLines. This C# method receives a file name, and returns an array. This array contains a string for each line in the file specified.
C# method info. We use this C# method. We then look inside its .NET implementation to see how it works. It is found in the System.IO namespace.
File
Example. This example program specifies a file on the disk. ReadAllLines() gets a string array from the file. The string array returned can be used as any other string array.
Then We can use "foreach" or "for" to loop over the file's data in a clean and intuitive way.
Loop, String Array
Tip This program reads in a file, counts its lines, and counts all chars in each line.
using System; using System.IO; class Program { static void Main() { string[] lines = File.ReadAllLines("C:\\rearrange.txt"); Console.WriteLine("Length: {0}", lines.Length); Console.WriteLine("First: {0}", lines[0]); int count = 0; foreach (string line in lines) { count++; } int c = 0; for (int i = 0; i < lines.Length; i++) { c++; } Console.WriteLine("Count: {0}", count); Console.WriteLine("C: {0}", c); } }
Length: 430 First: /_1=D1 Count: 430 C: 430
Implementation. File.ReadAllLines() uses a List and the StreamReader type, and then ToArray, to return the array. This is inefficient if you want to put a file into a List.
And Using lower-level file-handling methods (and avoiding a large array) could help speedup the IO here.
Notes, optimize. If you need to optimize a File.ReadAllLines call, you could estimate the capacity of the List in its constructor. You could also avoid ToArray if you want to keep the List.
List
StreamReader
ToArray
List Capacity
A summary. We looked at the File.ReadAllLines method. This is a convenience method that uses StreamReader and List internally. It can cause excess memory use.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 26, 2021 (image).
Home
Changes
© 2007-2025 Sam Allen