Here is the code to read a text file from disk one line at a time into a string. This code ensures the file exists and properly closes the file if an exception occurs.
Use these namespaces
using System;
using System.IO;
// Use this function
private void ReadTextFile(string filePath)
{
// initialize line to fill content each line
string line;
if (File.Exists(filePath)) // Check existence
{
StreamReader file = null; // initialize Reader
try
{
file = new StreamReader(filePath);
// Read line by line, stop if null.
while ((line = file.ReadLine()) != null)
{
// === Use each line ===
Console.WriteLine(line);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (file != null)
file.Close();
}
}
}