C# read text file | Best way to read file c sharp

How to read text file in c#:

In c sharp it is very easy to read a complete text file

// This function will return complete text in string format
public string ReadCompleteFile(string filePath)
{
     return System.IO.File.ReadAllText(filePath);
}

If you want to read text file line by line then follow this example code:

[sociallocker]

public string ReadTextFielLineByLine(string filePath)
{
	string fileText = "";
// Check if file is exists
	if (!File.Exists(filePath))
	{
		// File don't exist.
		return "";
	}
	using (StreamReader sr = File.OpenText(filePath))
	{
		String input;
		while ((input = sr.ReadLine()) != null)
		{
			fileText += input;
		}
	}
	return fileText;
}

[/sociallocker]

Leave a comment

Your email address will not be published. Required fields are marked *