File Handling in C# is a powerful feature provided by the .NET framework through the System.IO namespace. It allows developers to create, read, write, append, delete, and manipulate files and directories in a secure and efficient way. Whether you're building desktop applications, services, or backend logic, understanding C# file I/O is essential for working with persistent data.
File handling allows C# applications to persist data between sessions, log user activities, store configurations, export reports, and process large datasets. It is critical for building robust software systems that interact with the file system.
The System.IO namespace contains essential classes for file handling, including:
The static File class provides high-level operations for file management such as creating, reading, writing, appending, and deleting files.
string path = "example.txt";
File.Create(path).Close(); // Close to release the handle
File.WriteAllText("example.txt", "Welcome to File Handling in C#");
string content = File.ReadAllText("example.txt");
Console.WriteLine(content);
File.AppendAllText("example.txt", "\nAppended line.");
if (File.Exists("example.txt"))
{
Console.WriteLine("File exists.");
}
FileStream is used for low-level file operations. It supports reading/writing bytes and working with binary data.
using System.IO;
string path = "streamfile.txt";
string data = "Data written using FileStream";
byte[] byteData = System.Text.Encoding.UTF8.GetBytes(data);
using (FileStream fs = new FileStream(path, FileMode.Create))
{
fs.Write(byteData, 0, byteData.Length);
}
using (FileStream fs = new FileStream("streamfile.txt", FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string content = System.Text.Encoding.UTF8.GetString(buffer);
Console.WriteLine(content);
}
StreamReader is optimized for reading text data.
using (StreamReader reader = new StreamReader("example.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
StreamWriter is used for writing text data to files efficiently.
using (StreamWriter writer = new StreamWriter("log.txt"))
{
writer.WriteLine("This is a log entry.");
writer.WriteLine("Timestamp: " + DateTime.Now);
}
There are several ways to append text to an existing file:
File.AppendAllText("log.txt", "Appended at: " + DateTime.Now + "\n");
using (StreamWriter writer = new StreamWriter("log.txt", true))
{
writer.WriteLine("Another log entry.");
}
You can delete a file using the File.Delete method.
if (File.Exists("example.txt"))
{
File.Delete("example.txt");
Console.WriteLine("File deleted.");
}
Directory.CreateDirectory("Reports");
string[] files = Directory.GetFiles("Reports");
foreach (string file in files)
{
Console.WriteLine(file);
}
if (Directory.Exists("Reports"))
{
Directory.Delete("Reports", true); // true to delete recursively
}
File operations often involve external resources, so it's essential to use try-catch blocks to handle exceptions.
try
{
string content = File.ReadAllText("example.txt");
Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File not found: " + ex.Message);
}
catch (IOException ex)
{
Console.WriteLine("IO Error: " + ex.Message);
}public class Logger
{
private string logPath = "log.txt";
public void Log(string message)
{
using (StreamWriter writer = new StreamWriter(logPath, true))
{
writer.WriteLine($"{DateTime.Now}: {message}");
}
}
public void ReadLog()
{
if (File.Exists(logPath))
{
string content = File.ReadAllText(logPath);
Console.WriteLine(content);
}
else
{
Console.WriteLine("No log file found.");
}
}
}
Logger logger = new Logger();
logger.Log("User logged in");
logger.ReadLog();
File Handling in C# is a crucial part of application development for tasks such as logging, reading configurations, writing reports, and more. The .NET framework provides rich APIs via the System.IO namespace to interact with files and directories easily. By using classes like File, FileStream, StreamReader, StreamWriter, Directory, and handling exceptions gracefully, you can build robust and efficient file-handling routines for your applications.
Copyrights © 2024 letsupdateskills All rights reserved