Working With Files in .NET Using C#

R M Shahidul Islam Shahed
Programming with C#
3 min readAug 9, 2024

--

Working with files in .NET involves several key classes and methods provided by the framework to handle file operations.

Working With Files in .NET Using C#

Here are some fundamental tasks and corresponding examples using C#:

Reading from a File

To read text from a file, you can use StreamReader:

Working With Files in .NET Using C#

Output:

Working With Files in .NET Using C#

For Copy Code:

using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = @"E:\Data_\TMP_\Lorem_Ipsum.txt";

try
{
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

Writing to a File

--

--