File and Directory Operations in C# Programming


In C#, file and directory operations can be performed using classes in the System.IO namespace. This tutorial will cover common tasks such as reading and writing text files, working with binary files, and using classes like File, FileInfo, Directory, and DirectoryInfo for file and directory manipulation.

Step 1: Reading and Writing Text Files

C# provides the StreamReader and StreamWriter classes to read from and write to text files. Below are examples of how to use these classes:

Reading from a Text File using StreamReader

Here’s how to read the contents of a text file line by line using StreamReader:


    using System;
    using System.IO;
   namespace FileOperationsExample
    {
        class Program
        {
            static void Main()
            {
                // Path to the file
                string filePath = "example.txt";
               // Open the file for reading
                using (StreamReader reader = new StreamReader(filePath))
                {
                    string line;
                    // Read each line from the file
                    while ((line = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
        }
    }
        

In this example, we use StreamReader to open the file example.txt for reading. The ReadLine method reads each line of the file until the end of the file is reached.

Writing to a Text File using StreamWriter

Here’s how to write text to a file using StreamWriter:


    using System;
    using System.IO;
   namespace FileOperationsExample
    {
        class Program
        {
            static void Main()
            {
                // Path to the file
                string filePath = "output.txt";
               // Open the file for writing
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    // Write text to the file
                    writer.WriteLine("Hello, World!");
                    writer.WriteLine("Welcome to file operations in C#!");
                }
               Console.WriteLine("Text written to file.");
            }
        }
    }
        

In this example, we use StreamWriter to open a file called output.txt and write lines of text to it using the WriteLine method.

Step 2: Binary File Handling

In addition to working with text files, you can also handle binary files using the BinaryReader and BinaryWriter classes. These classes allow you to read and write binary data to a file.

Reading from a Binary File using BinaryReader

Here’s how to read binary data from a file using BinaryReader:


    using System;
    using System.IO;
   namespace FileOperationsExample
    {
        class Program
        {
            static void Main()
            {
                // Path to the binary file
                string filePath = "example.dat";
               // Open the file for reading
                using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
                {
                    // Read data from the file
                    int number = reader.ReadInt32();
                    double pi = reader.ReadDouble();
                   Console.WriteLine("Number: " + number);
                    Console.WriteLine("Pi: " + pi);
                }
            }
        }
    }
        

In this example, we use BinaryReader to read an integer and a double from a binary file example.dat.

Writing to a Binary File using BinaryWriter

Here’s how to write binary data to a file using BinaryWriter:


    using System;
    using System.IO;
   namespace FileOperationsExample
    {
        class Program
        {
            static void Main()
            {
                // Path to the binary file
                string filePath = "output.dat";
               // Open the file for writing
                using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))
                {
                    // Write data to the file
                    writer.Write(42);
                    writer.Write(3.14159);
                }
               Console.WriteLine("Binary data written to file.");
            }
        }
    }
        

In this example, we use BinaryWriter to write an integer and a double to the binary file output.dat.

Step 3: Working with File, FileInfo, Directory, and DirectoryInfo

C# provides several classes for working with files and directories, including File, FileInfo, Directory, and DirectoryInfo. These classes provide methods for creating, deleting, moving, copying, and manipulating files and directories.

Using the File Class

The File class provides static methods for file operations, such as checking if a file exists, copying, moving, and deleting files.


    using System;
    using System.IO;
   namespace FileOperationsExample
    {
        class Program
        {
            static void Main()
            {
                string sourceFile = "source.txt";
                string destinationFile = "destination.txt";
               // Check if the file exists
                if (File.Exists(sourceFile))
                {
                    // Copy the file to a new location
                    File.Copy(sourceFile, destinationFile);
                   // Delete the source file
                    File.Delete(sourceFile);
                   Console.WriteLine("File copied and deleted.");
                }
                else
                {
                    Console.WriteLine("Source file does not exist.");
                }
            }
        }
    }
        

In this example, we check if a file exists using File.Exists, copy it to a new location with File.Copy, and delete it with File.Delete.

Using the FileInfo Class

The FileInfo class provides instance methods for working with files, including getting file properties and performing operations like moving or renaming files.


    using System;
    using System.IO;
   namespace FileOperationsExample
    {
        class Program
        {
            static void Main()
            {
                string filePath = "example.txt";
               // Create a FileInfo object
                FileInfo fileInfo = new FileInfo(filePath);
               // Display file properties
                Console.WriteLine("File Name: " + fileInfo.Name);
                Console.WriteLine("File Size: " + fileInfo.Length + " bytes");
               // Rename the file
                string newFileName = "renamed_example.txt";
                fileInfo.MoveTo(newFileName);
               Console.WriteLine("File renamed to " + newFileName);
            }
        }
    }
        

In this example, we use the FileInfo class to get the file name and size. We also rename the file using the MoveTo method.

Using the Directory Class

The Directory class provides static methods for directory operations, such as creating, moving, and deleting directories.


    using System;
    using System.IO;
   namespace FileOperationsExample
    {
        class Program
        {
            static void Main()
            {
                string directoryPath = "exampleDirectory";
               // Create a directory
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                    Console.WriteLine("Directory created.");
                }
               // Delete the directory
                Directory.Delete(directoryPath);
                Console.WriteLine("Directory deleted.");
            }
        }
    }
        

In this example, we use the Directory class to create and delete a directory.

Using the DirectoryInfo Class

The DirectoryInfo class provides instance methods for directory operations, including getting directory properties and performing operations like moving or renaming directories.


    using System;
    using System.IO;
   namespace FileOperationsExample
    {
        class Program
        {
            static void Main()
            {
                string directoryPath = "exampleDirectory";
               // Create a DirectoryInfo object
                DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
               // Display directory properties
                Console.WriteLine("Directory Name: " + dirInfo.Name);
                Console.WriteLine("Full Path: " + dirInfo.FullName);
               // Rename the directory
                string newDirectoryName = "renamedDirectory";
                dirInfo.MoveTo(newDirectoryName);
               Console.WriteLine("Directory renamed to " + newDirectoryName);
            }
        }
    }
        

In this example, we use the DirectoryInfo class to get the directory name and full path. We also rename the directory using the MoveTo method.

Conclusion

In this tutorial, we covered several file and directory operations in C#, including:

  • Reading and writing text files with StreamReader and StreamWriter
  • Working with binary files using BinaryReader and BinaryWriter
  • Manipulating files and directories using File, FileInfo, Directory, and DirectoryInfo

These operations are essential for working with files and directories in C# applications, making it easier to read, write, manipulate, and organize your data.




Advertisement