C# - Read a file line by line
The code to read a file line by line and display its contents.
CODE
using System;
using System.IO;
public class Test
{
public static void Main(string[] args)
{
//call the function
string fileFullName = @"C:\Test\Test\sample.txt";
ReadFile(fileFullName);
Console.Write("\nPress any key to continue: ");
Console.ReadKey();
}
public static void ReadFile(string fileFullName)
{
//check if the file exists
if (File.Exists(fileFullName))
{
//if the file exists, proceed with the logic
//read all the lines and store it in an array
string[] lines = File.ReadAllLines(fileFullName);
//loop through each element in the array
foreach (string line in lines)
{
//display each element; that is display each line
Console.WriteLine(line);
}
}
else
{
//if the file doesn't exists, display an error message.
Console.WriteLine("The File {0} does not exist.", fileFullName);
}
}
}
INPUT & OUTPUT
Comments
Post a Comment