Working with Files in C# using the `FileInfo` Class: An Object-Oriented Approach

Learn how to use C#'s `FileInfo` class for object-oriented file operations. This tutorial explains `FileInfo`'s properties and methods, demonstrates file creation, reading, and writing, and emphasizes robust error handling for building reliable file-handling applications in C#.



Working with Files in C# using the `FileInfo` Class

Understanding the `FileInfo` Class

The C# `FileInfo` class (part of the `System.IO` namespace) provides an object-oriented way to work with files. Unlike static methods in the `File` class, `FileInfo` works with file objects, offering a more structured approach to file operations (creating, deleting, reading, writing, getting information about files). It's a sealed class, meaning you cannot inherit from it. Before using `FileInfo`, you must add `using System.IO;` to your code.

`FileInfo` Class Members

The `FileInfo` class includes several constructors, properties, and methods:

Constructors

Constructor Description
FileInfo(string path) Creates a `FileInfo` object for the given file path.

Properties

Property Description
Attributes Gets or sets file attributes (e.g., read-only, hidden).
CreationTime Gets or sets the file's creation time.
Directory Gets a `DirectoryInfo` object representing the file's parent directory.
DirectoryName Gets the full path of the directory containing the file.
Exists Indicates whether the file exists.
Extension Gets the file's extension (e.g., ".txt").
FullName Gets the file's full path.
IsReadOnly Gets or sets whether the file is read-only.
LastAccessTime Gets or sets the last access time.
Length Gets the file's size in bytes.
Name Gets the file's name.

Methods

Method Description
AppendText() Creates a `StreamWriter` to append text to the file.
CopyTo() Copies the file to a new location.
Create() Creates a new empty file.
CreateText() Creates a `StreamWriter` to write to a new text file.
Decrypt() Decrypts an encrypted file.
Delete() Deletes the file.
Encrypt() Encrypts the file.
GetAccessControl() Gets the file's access control list (ACL).
MoveTo() Moves the file to a new location.
Open() Opens the file with specified mode.
OpenRead() Opens the file for reading.
OpenText() Opens the file for reading text.
OpenWrite() Opens the file for writing.
Refresh() Refreshes the file information.
Replace() Replaces an existing file with a new file.
ToString() Returns a string representation of the file path.

Examples: Creating, Writing to, and Reading from a File

These examples demonstrate creating a file, writing to it using `StreamWriter`, and then reading from it using `StreamReader`. Remember to handle exceptions and replace `"F:\\abc.txt"` with an actual path. The examples include error handling using `try-catch` blocks.

Creating a File

C# Code

using System;
using System.IO;

public class FileInfoExample {
    public static void Main(string[] args) {
        FileInfo file = new FileInfo(@"F:\abc.txt"); // Replace with your path
        try {
            file.Create();
            Console.WriteLine("File created successfully.");
        } catch (Exception ex) {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Writing to a File

C# Code

using System;
using System.IO;

public class FileInfoExample {
    public static void Main(string[] args) {
        // ... (FileInfo creation) ...
        using (StreamWriter writer = file.CreateText()) {
            writer.WriteLine("Example text.");
        }
    }
}

Reading from a File

C# Code

using System;
using System.IO;

public class FileInfoExample {
    public static void Main(string[] args) {
        // ... (FileInfo creation) ...
        using (StreamReader reader = file.OpenText()) {
            string line;
            while ((line = reader.ReadLine()) != null) {
                Console.WriteLine(line);
            }
        }
    }
}

Conclusion

The `FileInfo` class provides a structured and object-oriented way to work with files in C#. Understanding its properties and methods, along with robust error handling, is essential for building reliable and efficient file-handling capabilities into your applications.