Skip to content

File Handling

Sann Lynn Htun edited this page Nov 19, 2024 · 1 revision

C# File Handling

File handling in C# is essential for performing various operations like reading from, writing to, and manipulating files. The System.IO namespace contains the necessary classes for file operations.

Key Concepts

  1. Reading and Writing Files

Use StreamReader and StreamWriter for text files and FileStream for binary files.

Examples

Reading from a File

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        using (StreamReader reader = new StreamReader(path))
        {
            string content = reader.ReadToEnd();
            Console.WriteLine(content);
        }
    }
}

Writing to a File

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        using (StreamWriter writer = new StreamWriter(path))
        {
            writer.WriteLine("Hello, World!");
        }
    }
}

Advanced Features

  1. FileStream

Use FileStream for more control over file operations, especially for binary data.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.bin";
        using (FileStream fs = new FileStream(path, FileMode.Create))
        {
            byte[] data = { 0, 1, 2, 3, 4, 5 };
            fs.Write(data, 0, data.Length);
        }
    }
}
  1. File Class

The File class provides static methods for common file operations, such as copying, deleting, and checking the existence of files.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string sourcePath = "source.txt";
        string destinationPath = "destination.txt";

        // Copy file
        File.Copy(sourcePath, destinationPath, true);

        // Check if file exists
        if (File.Exists(destinationPath))
        {
            Console.WriteLine("File copied successfully.");
        }

        // Delete file
        File.Delete(destinationPath);
    }
}

Summary

  • StreamReader and StreamWriter: For reading and writing text files.
  • FileStream: For binary file operations.
  • File Class: For common file operations like copy, delete, and check existence.

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally