C# Program to read all the lines one by one in a file

CsharpProgrammingServer Side Programming

Use ReadAllLines() method to read all the lines one by one in a file.

Let’s say we have a file “new.txt” with the following lines.

One
Two
Three

Firstly, set the path of the file to be read.

String myPath = "new.txt";

Now add it under a string array to fetch the lines on by one.

String[] fLine = File.ReadAllLines(myPath);

Let’s say you need to fetch the first line. For that.

fLine[0]

The following is the complete example that reads lines one by one in a file.

Example

using System;
using System.IO;
public class Demo {
   public static void Main() {
      String myPath = "new.txt";
      String[] fLine;
      // array of lines in a file
      fLine = File.ReadAllLines(myPath);
      // read lines of a file
      Console.WriteLine("Line 1: "+fLine[0]);
      Console.WriteLine("Line 2: "+fLine[1]);
      Console.WriteLine("Line 3: "+fLine[2]);
      Console.WriteLine("Line 4 "+fLine[3]);
   }
}

Output

Line1: One
Line2: Two
Line3: Three
Line4: Four
raja
Published on 14-Sep-2018 11:53:35
Advertisements