Updated April 1, 2023
Introduction to C# Read File
Performing file operations is an integral part of the programmer’s life and all the programming languages provide various libraries or functions to achieve the same. The same can be done in C# using the methods available in the File class provider. Generally reading from a file is performed using the two methods ReadAllText(file) and ReadAllLines(file), where the file denotes the file that needs to be read. Files can also be read using the Streamreader as bytes. This article will cover in detail the various methods that are available in C# for reading a file along with appropriate examples.
Syntax:
The ReadAllText() has the following syntax
public static string ReadAllText (String Path, System.Text.Encoding encoding)
The ReadAllLines() has the following syntax
public static string ReadAllLines(String, Encoding)
This method reads all the lines that are present in the file and then stores them in a string and then closes the file.
Parameters of C# Read File
- Path: The path contains the location of the files. This file must be read.
- Encoding: This denotes the encoding type of the file, this is optional.
The return type of this method is a string that has all the contents in the file. This method is available in the System.IO namespace and the assembly that is associated with this method is mscorlib.dll.
Exceptions associated with ReadAllText() of ReadAllLines() method:
- Argument Exception: This occurs when the path has zero characters, white spaces, or invalid characters.
- Argument Null Exception: This occurs when the path is null.
- Path Too Long Exception: This occurs when the path exceeds the actual system defined limit.
- IO Exception: When opening the file if any error occurs, this exception occurs.
- UnAuthorized Access Exception: This occurs when the specified file is read only
- File Not Found Exception: This occurs when the file is not there in the specified location.
- Not Supported Exception: When the specified path is in invalid format, this exception is thrown.
- Security Exception: When the user doesn’t have access to the file, this exception is thrown.
Examples of C# Read File
Here are the following examples mentioned below.
Example#1 – Reading a file using ReadAllText()
Code:
using System;
using System.IO;
using System.Text;
namespace ReadAllText
{
class Test
{
static void Main(string[] args)
{
var Fpath= @"C:\Vignesh\KB.txt";
string content = File.ReadAllText(Fpath, Encoding.UTF8);
Console.WriteLine(content);
}
}
}
Output:
Example #2 – Reading a file using ReadAllLines()
Code:
using System;
using System.IO;
using System.Text;
namespace ReadAllLines
{
class Test
{
static void Main(string[] args)
{
var inputfile = @"C:\Vignesh\append.txt";
string[] output = File.ReadAllLines(inputfile, Encoding.UTF8);
foreach (string op in output)
{
Console.WriteLine(op);
}
}
}
}
Output:
Example #3 – Reading a file using streamreader class
1. StreamReader.ReadToEnd(): This method is used to read the file from the current position to the end of the stream. The corresponding namespace for this method is System.Io and assembly is mscorblib.dll.
Syntax:
public override string ReadToEnd ();
Input Parameters: This method doesn’t require any input parameter.
Returns: This method outputs the file content as stream, if the current position is set to last character of the file an empty string is returned.
2. StreamReader.ReadLine(): This method reads the characters from the current stream and sends the data as a string to the output. The corresponding namespace for this method is System.Io and assembly is mscorblib.dll.
Syntax:
public override string ReadLine();
Input Parameters: This method doesn’t require any input parameter.
Returns: It returns the next line to the current stream, if the current stream is in the last line position then null is returned.
Code:
using System;
using System.IO;
using System.Text;
class Program
{
static void Main(string[] args)
{
var FP = @"C:\Vignesh\Names.txt";
using var fstre = new FileStream(FP, FileMode.Open, FileAccess.Read);
using var sree = new StreamReader(fstre, Encoding.UTF8);
string Fcontent = sree.ReadToEnd();
Console.WriteLine(Fcontent);
}
}
Output:
Code:
using System;
using System.IO;
using System.Text;
class Program
{
static void Main(string[] args)
{
var filpath = @"C:\Vignesh\TimerJob-2019-08-09.txt";
using var fstre = new FileStream(filpath, FileMode.Open, FileAccess.Read);
using var sreee = new StreamReader(fstre, Encoding.UTF8);
string cline = String.Empty;
while ((cline = sreee.ReadLine()) != null)
{
Console.WriteLine(cline);
}
}
}
Output:
Code:
using System;
using System.IO;
namespace testclass {
class Test {
string FPath = @ "C:\Vignesh\Script to 0365 connection.txt";
static void Main(string[] args)
{
//Check if file is there at the path
//ReadallOutput()
if (File.Exists(FPath)) {
string output = File.ReadAlloutput(FPath);
Console.WriteLine(output);
}
//Check if file is there at the path
if (File.Exists(FPath)) {
//ReadallLines()
string[] Flines = File.ReadAllFlines(FPath);
foreach(string line in Flines)
Console.WriteLine(line);
}
//Check if file is there at the path
if (File.Exists(FPath)) {
//using streamreader
using(StreamReader file = new StreamReader(FPath)) {
int counter = 0;
string lgth;
while ((lgth = file.ReadLine()) != null) {
Console.WriteLine(lgth);
counter++;
}
file.Close();
}
}
Console.ReadKey();
}
}
}
Output:
Example #4 – Reading a file asynchronously using streamreader
Code:
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
class TestProgram
{
static async Task Main(string[] args)
{
var ip = @" C:\Vignesh\Patching\Patching Steps.txt";
using var fssss = new FileStream(ip, FileMode.Open, FileAccess.Read);
using var srrr = new StreamReader(fssss, Encoding.UTF8);
//Reading asynchronously
string op = await srrr.ReadToEndAsync();
Console.WriteLine(op);
}
}
Output:
Conclusion
Thus, the article covered in detail the read file functionality in c#. It explained the various methods that are available to perform the operation. It also covered various parameters and exceptions that are associated with each method and explained in detail along with the example of sample programs. To cover more in detail, it is advisable to write sample programs and practice them.
Recommended Articles
This is a guide to C# Read File. Here we discuss the various methods that are available in C# for reading a file along with appropriate examples. You may also have a look at the following articles to learn more –