Working With Files in .NET Using C#
Published in
3 min readAug 9, 2024
Working with files in .NET involves several key classes and methods provided by the framework to handle file operations.
Here are some fundamental tasks and corresponding examples using C#:
Reading from a File
To read text from a file, you can use StreamReader
:
Output:
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);
}
}
}