C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Print: The program successfully prints the data found in the file.txt file in the C directory.
Important: With File.ReadLines, the foreach-loop is the best syntax as it avoids copying the IEnumerable to another collection in memory.
ForeachIEnumerableC# program that uses File.ReadLines
using System;
using System.IO;
class Program
{
static void Main()
{
// Read in lines from file.
foreach (string line in File.ReadLines("c:\\file.txt"))
{
Console.WriteLine("-- {0}", line);
}
}
}
Output
-- Line1
-- Line2
-- Line3
-- Another line.
-- Last line.
Thus: The File.ReadAllLines method is best if you need the entire array. An example of it is available.
File.ReadAllLines