C# - File Handling in C#

File Handling in C# - Complete Tutorial with Examples

File Handling in C#

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.

Why File Handling is Important in C#?

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.

System.IO Namespace

The System.IO namespace contains essential classes for file handling, including:

  • File
  • FileInfo
  • Directory
  • DirectoryInfo
  • StreamReader
  • StreamWriter
  • FileStream
  • BinaryReader / BinaryWriter

The File Class in C#

The static File class provides high-level operations for file management such as creating, reading, writing, appending, and deleting files.

Create a File

string path = "example.txt";
File.Create(path).Close(); // Close to release the handle

Write Text to File

File.WriteAllText("example.txt", "Welcome to File Handling in C#");

Read Text from File

string content = File.ReadAllText("example.txt");
Console.WriteLine(content);

Append Text to File

File.AppendAllText("example.txt", "\nAppended line.");

Check File Exists

if (File.Exists("example.txt"))
{
    Console.WriteLine("File exists.");
}

Using FileStream in C#

FileStream is used for low-level file operations. It supports reading/writing bytes and working with binary data.

Write Using FileStream

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);
}

Read Using FileStream

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);
}

Reading Files Using StreamReader

StreamReader is optimized for reading text data.

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

Writing Files Using StreamWriter

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);
}

Appending Text to Files in C#

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.");
}

Deleting Files in C#

You can delete a file using the File.Delete method.

if (File.Exists("example.txt"))
{
    File.Delete("example.txt");
    Console.WriteLine("File deleted.");
}

Working with Directories

Create a Directory

Directory.CreateDirectory("Reports");

List Files in a Directory

string[] files = Directory.GetFiles("Reports");

foreach (string file in files)
{
    Console.WriteLine(file);
}

Delete Directory

if (Directory.Exists("Reports"))
{
    Directory.Delete("Reports", true); // true to delete recursively
}

File Handling with Exception Handling

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);
}

Real-World Example: Logging System

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.

Beginner 5 Hours
File Handling in C# - Complete Tutorial with Examples

File Handling in C#

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.

Why File Handling is Important in C#?

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.

System.IO Namespace

The System.IO namespace contains essential classes for file handling, including:

  • File
  • FileInfo
  • Directory
  • DirectoryInfo
  • StreamReader
  • StreamWriter
  • FileStream
  • BinaryReader / BinaryWriter

The File Class in C#

The static File class provides high-level operations for file management such as creating, reading, writing, appending, and deleting files.

Create a File

string path = "example.txt"; File.Create(path).Close(); // Close to release the handle

Write Text to File

File.WriteAllText("example.txt", "Welcome to File Handling in C#");

Read Text from File

string content = File.ReadAllText("example.txt"); Console.WriteLine(content);

Append Text to File

File.AppendAllText("example.txt", "\nAppended line.");

Check File Exists

if (File.Exists("example.txt")) { Console.WriteLine("File exists."); }

Using FileStream in C#

FileStream is used for low-level file operations. It supports reading/writing bytes and working with binary data.

Write Using FileStream

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); }

Read Using FileStream

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); }

Reading Files Using StreamReader

StreamReader is optimized for reading text data.

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

Writing Files Using StreamWriter

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); }

Appending Text to Files in C#

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."); }

Deleting Files in C#

You can delete a file using the File.Delete method.

if (File.Exists("example.txt")) { File.Delete("example.txt"); Console.WriteLine("File deleted."); }

Working with Directories

Create a Directory

Directory.CreateDirectory("Reports");

List Files in a Directory

string[] files = Directory.GetFiles("Reports"); foreach (string file in files) { Console.WriteLine(file); }

Delete Directory

if (Directory.Exists("Reports")) { Directory.Delete("Reports", true); // true to delete recursively }

File Handling with Exception Handling

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); }

Real-World Example: Logging System

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.

Related Tutorials

Frequently Asked Questions for General

line

Copyrights © 2024 letsupdateskills All rights reserved