Introduction

File I/O (Input/Output) is a fundamental concept in programming that allows you to read from and write to files. In C#, the System.IO namespace provides various classes for handling file operations. This module will cover the basics of file I/O, including reading from and writing to text files, handling binary files, and working with file streams.

Key Concepts

  1. File Handling Classes: File, FileInfo, StreamReader, StreamWriter, BinaryReader, BinaryWriter.
  2. Reading and Writing Text Files: Using StreamReader and StreamWriter.
  3. Reading and Writing Binary Files: Using BinaryReader and BinaryWriter.
  4. File Streams: Understanding FileStream for more control over file operations.

File Handling Classes

File and FileInfo

  • File: Provides static methods for creating, copying, deleting, moving, and opening files.
  • FileInfo: Provides instance methods for the same operations but allows for more detailed file manipulation.

Comparison Table

Feature File (Static) FileInfo (Instance)
Creation Yes Yes
Deletion Yes Yes
Copying Yes Yes
Moving Yes Yes
Opening Yes Yes
Detailed Info No Yes

Reading and Writing Text Files

Reading Text Files

To read text from a file, you can use the StreamReader class.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        
        // Ensure the file exists
        if (File.Exists(path))
        {
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        else
        {
            Console.WriteLine("File not found.");
        }
    }
}

Writing Text Files

To write text to a file, you can use the StreamWriter class.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        
        using (StreamWriter sw = new StreamWriter(path))
        {
            sw.WriteLine("Hello, World!");
            sw.WriteLine("This is a text file.");
        }
        
        Console.WriteLine("Text written to file.");
    }
}

Reading and Writing Binary Files

Reading Binary Files

To read binary data from a file, you can use the BinaryReader class.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.bin";
        
        if (File.Exists(path))
        {
            using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open)))
            {
                int intValue = br.ReadInt32();
                double doubleValue = br.ReadDouble();
                
                Console.WriteLine($"Integer: {intValue}, Double: {doubleValue}");
            }
        }
        else
        {
            Console.WriteLine("File not found.");
        }
    }
}

Writing Binary Files

To write binary data to a file, you can use the BinaryWriter class.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.bin";
        
        using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))
        {
            bw.Write(42);
            bw.Write(3.14159);
        }
        
        Console.WriteLine("Binary data written to file.");
    }
}

File Streams

For more control over file operations, you can use the FileStream class.

Example: Using FileStream to Read and Write

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        
        // Writing to a file using FileStream
        using (FileStream fs = new FileStream(path, FileMode.Create))
        {
            byte[] info = new UTF8Encoding(true).GetBytes("Hello, FileStream!");
            fs.Write(info, 0, info.Length);
        }
        
        // Reading from a file using FileStream
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            
            while (fs.Read(b, 0, b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}

Practical Exercises

Exercise 1: Reading a Text File

  1. Create a text file named data.txt with some sample text.
  2. Write a C# program to read and display the contents of the file.

Solution:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "data.txt";
        
        if (File.Exists(path))
        {
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        else
        {
            Console.WriteLine("File not found.");
        }
    }
}

Exercise 2: Writing to a Binary File

  1. Write a C# program to write an integer and a double to a binary file named data.bin.
  2. Write another program to read and display the values from data.bin.

Solution:

// Writing to a binary file
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "data.bin";
        
        using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))
        {
            bw.Write(123);
            bw.Write(45.67);
        }
        
        Console.WriteLine("Binary data written to file.");
    }
}
// Reading from a binary file
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "data.bin";
        
        if (File.Exists(path))
        {
            using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open)))
            {
                int intValue = br.ReadInt32();
                double doubleValue = br.ReadDouble();
                
                Console.WriteLine($"Integer: {intValue}, Double: {doubleValue}");
            }
        }
        else
        {
            Console.WriteLine("File not found.");
        }
    }
}

Conclusion

In this module, you learned how to perform basic file I/O operations in C#. You explored the System.IO namespace and its classes, such as File, FileInfo, StreamReader, StreamWriter, BinaryReader, BinaryWriter, and FileStream. You also practiced reading and writing both text and binary files. Understanding these concepts is crucial for handling data storage and retrieval in real-world applications.

© Copyright 2024. All rights reserved