Skip to main content

Reading from Files

Introduction

In C#, the process of reading from a file is an essential skill for any developer. Whether you're working with text files, CSVs, or other types of data files, being able to effectively read from them can greatly enhance your programming capabilities. In this tutorial, we will explore how to read from files using various methods in C#.

System.IO Namespace

To work with files in C#, we need to use the System.IO namespace. This namespace contains various classes that provide a rich set of system-independent input and output (I/O) services for .NET applications.

To use this namespace, you need to include the following line at the top of your C# program:

using System.IO;

Reading Text Files

The StreamReader class in the System.IO namespace allows us to read a text file. Here's a simple example of how you can use this class to read a text file:

using (StreamReader reader = new StreamReader("test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}

In this example, we are using a StreamReader to read from a file called test.txt. We read the file line by line using the ReadLine method and print each line to the console.

Reading Binary Files

For binary files, we use a different class from the System.IO namespace - the BinaryReader class. Below is an example of how to read a binary file:

using (BinaryReader reader = new BinaryReader(File.Open("test.bin", FileMode.Open)))
{
Console.WriteLine(reader.ReadBoolean());
Console.WriteLine(reader.ReadInt32());
Console.WriteLine(reader.ReadString());
}

In this example, we're reading a binary file named test.bin. The BinaryReader class provides methods to read different types of data from the file including booleans, integers, and strings.

Reading CSV Files

Reading a CSV file is similar to reading a text file. However, we need to additionally parse each line to get the individual fields. Here's a simple example:

using (StreamReader reader = new StreamReader("test.csv"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] fields = line.Split(',');
foreach (string field in fields)
{
Console.WriteLine(field);
}
}
}

In this example, we're reading a CSV file named test.csv. After reading each line, we split the line into fields using the Split method and print each field to the console.

Conclusion

In this tutorial, we explored different methods to read from files in C#. We covered text files, binary files, and CSV files. Remember, the System.IO namespace is your friend when working with file I/O in C#. Always close your streams after you're done to free up system resources. And most importantly, always handle exceptions that may occur during file I/O to prevent your program from crashing unexpectedly. Happy coding!