;

C# FileInfo


The FileInfo class in C# is a powerful tool for working with files in an object-oriented way. It allows you to easily manipulate files, get file metadata, and perform various file operations. In this guide, we will cover all the methods and properties of the FileInfo class with detailed examples, real-world use cases, and a comprehensive summary to help you understand how to efficiently use FileInfo in your applications.

Introduction to FileInfo Class

The FileInfo class, part of the System.IO namespace, provides a variety of methods and properties to work with files. Unlike the static File class, FileInfo operates in an object-oriented manner, which makes it more efficient for handling files when multiple operations need to be performed. This class is useful for getting information about files, such as size, creation time, and for performing operations like copying, moving, and deleting files.

FileInfo Properties

The FileInfo class offers several properties that provide information about a file. Below is a list of all the properties, along with examples and explanations.

1. FullName

  • Description: Gets the full path of the file.
Example:
FileInfo fileInfo = new FileInfo(@"C:\temp\example.txt");
Console.WriteLine(fileInfo.FullName); // Output: C:\temp\example.txt

Use Case: Useful when you need to display the full path of a file or log file locations.

2. Name

  • Description: Gets the name of the file.
Example:
Console.WriteLine(fileInfo.Name); // Output: example.txt

Use Case: Retrieve just the name of a file without the full path.

3. Length

  • Description: Gets the size of the file in bytes.
Example:
Console.WriteLine(fileInfo.Length); // Output: File size in bytes

Use Case: To display or check the size of a file, such as when enforcing file size limits.

4. Extension

  • Description: Gets the file extension.
Example:
Console.WriteLine(fileInfo.Extension); // Output: .txt

Use Case: Determine the file type and apply specific logic based on the extension.

5. Directory

  • Description: Gets an instance of the DirectoryInfo representing the directory of the file.
Example:
DirectoryInfo dirInfo = fileInfo.Directory;
Console.WriteLine(dirInfo.FullName); // Output: Directory path

Use Case: Retrieve information about the directory that contains the file.

6. DirectoryName

  • Description: Gets the full path of the directory containing the file.
Example:
Console.WriteLine(fileInfo.DirectoryName); // Output: C:\temp

Use Case: Useful when logging or for further operations related to the directory.

7. CreationTime and CreationTimeUtc

  • Description: Gets or sets the time when the file was created.
Example:
Console.WriteLine(fileInfo.CreationTime); // Output: File creation time
  • Use Case: To track when a file was created, useful for logging or auditing purposes.

8. LastAccessTime and LastAccessTimeUtc

  • Description: Gets or sets the time the file was last accessed.
Example:
Console.WriteLine(fileInfo.LastAccessTime); // Output: Last access time

Use Case: Useful for monitoring file usage and determining if a file is stale.

9. LastWriteTime and LastWriteTimeUtc

  • Description: Gets or sets the time the file was last written to.
Example:
Console.WriteLine(fileInfo.LastWriteTime); // Output: Last write time
  • Use Case: Track changes to files for version control or backup purposes.

10. Attributes

  • Description: Gets or sets the file attributes (e.g., read-only, hidden).
Example:
Console.WriteLine(fileInfo.Attributes); // Output: File attributes

Use Case: Modify file attributes for permissions or make a file hidden.

FileInfo Methods

The FileInfo class provides various methods to manipulate files. Here are some of the most important methods:

1. Create()

  • Description: Creates a new file.
Example:
using (FileStream fs = fileInfo.Create())
{
    // Write data to the file if needed
}

Use Case: Create new files, such as when initializing log files.

2. CopyTo(string destination, bool overwrite = false)

  • Description: Copies the file to a new location.
Example:
fileInfo.CopyTo(@"C:\temp\copy_example.txt", true);
  • Use Case: Create backups or duplicate files.

3. Delete()

  • Description: Deletes the file.
Example:
fileInfo.Delete();
Console.WriteLine("File deleted successfully.");

Use Case: Delete old or unnecessary files.

4. MoveTo(string destination)

  • Description: Moves the file to a new location.
Example:
fileInfo.MoveTo(@"C:\temp\new_location.txt");
  • Use Case: Organize files or move them to archive directories.

5. Open(FileMode mode, FileAccess access, FileShare share)

  • Description: Opens a file in the specified mode with the specified access and sharing options.
Example:
using (FileStream fs = fileInfo.Open(FileMode.Open, FileAccess.Read))
{
    // Read from the file
}
  • Use Case: Flexible way to access the file for reading, writing, or both.

6. OpenRead()

  • Description: Opens the file in read-only mode.
Example:
using (FileStream fs = fileInfo.OpenRead())
{
    // Read from the file
}

Use Case: Efficient way to read from files without modifying them.

7. OpenWrite()

  • Description: Opens the file in write-only mode.
Example:
using (FileStream fs = fileInfo.OpenWrite())
{
    // Write to the file
}
  • Use Case: Use when you need to write to files without reading.

8. Replace(string destinationFileName, string destinationBackupFileName)

  • Description: Replaces the contents of a specified file with the file described by the FileInfo object.
Example:
fileInfo.Replace(@"C:\temp\file_to_replace.txt", @"C:\temp\backup.txt");
  • Use Case: Update existing files with newer versions and keep a backup.

Examples of FileInfo Usage

Example: Managing File Metadata

using System;
using System.IO;

class Program
{
    static void Main()
    {
        FileInfo fileInfo = new FileInfo(@"C:\temp\example.txt");

        if (!fileInfo.Exists)
        {
            using (FileStream fs = fileInfo.Create())
            {
                byte[] content = System.Text.Encoding.UTF8.GetBytes("Hello, FileInfo!");
                fs.Write(content, 0, content.Length);
            }
        }

        Console.WriteLine($"File Name: {fileInfo.Name}");
        Console.WriteLine($"File Size: {fileInfo.Length} bytes");
        Console.WriteLine($"Created On: {fileInfo.CreationTime}");
        Console.WriteLine($"Last Accessed: {fileInfo.LastAccessTime}");

        // Move file to a new location
        string newPath = @"C:\temp\example_moved.txt";
        fileInfo.MoveTo(newPath);
        Console.WriteLine($"File moved to: {newPath}");
    }
}

Explanation:

  • Creates a file if it doesn't exist.
  • Displays metadata like file name, size, creation time, and last accessed time.
  • Moves the file to a new location.

Real-World Example: Log File Manager

Let’s create a LogFileManager that creates log files, appends log messages, and provides metadata for each log file.

Example: Log File Manager

using System;
using System.IO;

class LogFileManager
{
    private FileInfo logFile;

    public LogFileManager(string logFilePath)
    {
        logFile = new FileInfo(logFilePath);
        if (!logFile.Exists)
        {
            using (FileStream fs = logFile.Create())
            {
                fs.Write(System.Text.Encoding.UTF8.GetBytes("Log File Created.\n"));
            }
        }
    }

    public void AppendLog(string message)
    {
        using (StreamWriter writer = logFile.AppendText())
        {
            writer.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}");
        }
    }

    public void DisplayLogMetadata()
    {
        Console.WriteLine($"Log File: {logFile.Name}");
        Console.WriteLine($"Size: {logFile.Length} bytes");
        Console.WriteLine($"Created On: {logFile.CreationTime}");
        Console.WriteLine($"Last Modified: {logFile.LastWriteTime}");
    }
}

class Program
{
    static void Main()
    {
        LogFileManager logManager = new LogFileManager(@"C:\temp\log.txt");

        logManager.AppendLog("Application started.");
        logManager.AppendLog("An event occurred.");
        logManager.AppendLog("Application stopped.");

        logManager.DisplayLogMetadata();
    }
}

Explanation:

  • LogFileManager Class:
    • Creates a log file if it doesn't already exist.
    • Appends log messages to the file with a timestamp.
    • Displays metadata for the log file, such as file size and creation time.
  • Usage:
    • AppendLog is used to add messages to the log file.
    • DisplayLogMetadata provides detailed information about the log file.

Use Case: This is useful for logging application events or errors, allowing you to maintain a comprehensive activity log.

Key Takeaways

  • FileInfo for File Metadata: The FileInfo class is ideal for accessing metadata about a file, such as its name, size, creation time, and modification time.
  • Efficient for Multiple Operations: When performing multiple operations on the same file, FileInfo is more efficient than repeatedly using the File class.
  • Object-Oriented File Handling: FileInfo provides an object-oriented approach, which is beneficial for organizing and managing file operations cleanly.
  • Useful Methods: Methods like Create(), CopyTo(), MoveTo(), and Delete() make FileInfo a versatile class for managing file system operations.
  • Real-World Use: Common use cases include managing log files, backups, configuration files, and any scenario where repeated file operations are required.

Summary

The FileInfo class in C# is a powerful and flexible tool for managing files in an object-oriented way. By using FileInfo, you can easily perform file operations, gather metadata, and handle files efficiently. The class provides numerous properties and methods, such as Length, CreationTime, MoveTo(), and Delete(), which make it an essential part of file management in C#.

Whether you are developing a simple console application or a complex enterprise solution, understanding and using FileInfo can help you manage files effectively, as demonstrated in the Log File Manager example. It is a versatile tool that simplifies many common file operations, making your code more readable and maintainable.