ZetCode

C# File Class

last modified April 20, 2025

This tutorial explains how to use the File class in C# to perform various file operations. The File class provides static methods for creating, copying, deleting, moving, and opening files.

The File class is part of the System.IO namespace and offers static methods for file operations. It simplifies working with files by providing ready-to-use functionality.

File methods are typically used for single file operations. For more complex scenarios, consider using FileStream or StreamReader/StreamWriter classes.

Checking File Existence

This example demonstrates how to check if a file exists before performing operations on it. The Exists method is used for this purpose.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "test.txt";
        
        if (File.Exists(filePath))
        {
            Console.WriteLine("File exists");
            Console.WriteLine($"Last write time: {File.GetLastWriteTime(filePath)}");
        }
        else
        {
            Console.WriteLine("File does not exist");
            File.Create(filePath).Close();
            Console.WriteLine("Created new file");
        }
    }
}

The program checks if a file exists and displays its last write time if it does. If the file doesn't exist, it creates a new empty file. The Exists method returns a boolean indicating whether the file exists at the specified path.

GetLastWriteTime retrieves the datetime when the file was last modified. File.Create creates a new file and returns a FileStream, which we immediately close since we don't need it. Always check file existence before operations to avoid exceptions.

Reading and Writing Text Files

The File class provides simple methods for reading and writing text files. This example shows basic file I/O operations.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "data.txt";
        
        // Write to file
        File.WriteAllText(filePath, "Hello File Class!\nThis is a second line.");
        
        // Append to file
        File.AppendAllText(filePath, "\nThis line was appended.");
        
        // Read from file
        string content = File.ReadAllText(filePath);
        Console.WriteLine("File content:");
        Console.WriteLine(content);
        
        // Read lines separately
        string[] lines = File.ReadAllLines(filePath);
        Console.WriteLine("\nLine count: " + lines.Length);
    }
}

WriteAllText creates or overwrites a file with the specified content. AppendAllText adds content to an existing file. ReadAllText reads the entire file content as a single string.

ReadAllLines reads the file content as an array of strings, with each element representing a line. These methods handle file opening, writing/reading, and closing automatically. They're convenient for small files but may not be suitable for very large files due to memory usage.

Copying and Moving Files

This example demonstrates file copying and moving operations using the File class methods.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string sourceFile = "source.txt";
        string destFile = "destination.txt";
        string movedFile = "moved.txt";
        
        // Create source file
        File.WriteAllText(sourceFile, "This is the source file content.");
        
        // Copy file
        File.Copy(sourceFile, destFile);
        Console.WriteLine($"File copied to {destFile}");
        
        // Move file
        File.Move(destFile, movedFile);
        Console.WriteLine($"File moved to {movedFile}");
        
        // Verify operations
        Console.WriteLine($"Source exists: {File.Exists(sourceFile)}");
        Console.WriteLine($"Destination exists: {File.Exists(destFile)}");
        Console.WriteLine($"Moved file exists: {File.Exists(movedFile)}");
    }
}

File.Copy creates a copy of the source file at the specified destination path. By default, it won't overwrite an existing file unless the overwrite parameter is set to true. File.Move transfers the file to a new location and can also be used to rename files.

The move operation is atomic when performed within the same volume. For cross-volume moves, it's actually a copy followed by delete. Always check file existence before these operations to avoid exceptions. These methods preserve file attributes and timestamps when possible.

File Information and Attributes

The File class provides methods to retrieve various file properties and attributes. This example shows how to access this information.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "info.txt";
        File.WriteAllText(filePath, "Sample content for file information demo.");
        
        // Get file information
        DateTime creationTime = File.GetCreationTime(filePath);
        DateTime lastWriteTime = File.GetLastWriteTime(filePath);
        DateTime lastAccessTime = File.GetLastAccessTime(filePath);
        FileAttributes attributes = File.GetAttributes(filePath);
        
        Console.WriteLine($"File: {filePath}");
        Console.WriteLine($"Created: {creationTime}");
        Console.WriteLine($"Last modified: {lastWriteTime}");
        Console.WriteLine($"Last accessed: {lastAccessTime}");
        Console.WriteLine($"Attributes: {attributes}");
        
        // Check specific attributes
        bool isReadOnly = (attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
        bool isHidden = (attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
        
        Console.WriteLine($"ReadOnly: {isReadOnly}");
        Console.WriteLine($"Hidden: {isHidden}");
    }
}

The example retrieves various timestamps and attributes of a file. GetCreationTime, GetLastWriteTime, and GetLastAccessTime return DateTime objects representing important file events. GetAttributes returns a bitmask of file attributes.

File attributes are checked using bitwise operations. The example checks for ReadOnly and Hidden flags. Other common attributes include Archive, System, and Directory. These methods are useful for file management applications and utilities that need to inspect file properties.

Deleting Files

This example demonstrates file deletion using the File class. It shows safe deletion practices and error handling.

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "temporary.txt";
        File.WriteAllText(filePath, "This file will be deleted.");
        
        Console.WriteLine($"File exists before deletion: {File.Exists(filePath)}");
        
        try
        {
            File.Delete(filePath);
            Console.WriteLine("File deleted successfully.");
            
            // Attempt to delete non-existent file
            File.Delete("nonexistent.txt");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        
        Console.WriteLine($"File exists after deletion: {File.Exists(filePath)}");
    }
}

File.Delete removes the specified file permanently. Unlike moving to recycle bin, this operation is irreversible. The method doesn't throw an exception if the file doesn't exist, making it safe to call without existence checks.

However, exceptions may occur for other reasons like insufficient permissions or file being in use. Always handle potential exceptions when performing file operations. For critical applications, consider implementing a backup or confirmation mechanism before deletion.

Working with File Streams

While the File class provides high-level methods, it can also create file streams for more control. This example shows stream-based file operations.

Program.cs
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string filePath = "streamdata.bin";
        
        // Write using FileStream
        using (FileStream fs = File.Create(filePath))
        {
            byte[] data = Encoding.UTF8.GetBytes("Stream-based file content");
            fs.Write(data, 0, data.Length);
            fs.Flush();
        }
        
        // Read using FileStream
        using (FileStream fs = File.OpenRead(filePath))
        {
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            string content = Encoding.UTF8.GetString(buffer);
            Console.WriteLine("Read content: " + content);
        }
        
        // Alternative open methods
        using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite))
        {
            // Can perform both read and write operations
            fs.Position = 0;
            byte[] newData = Encoding.UTF8.GetBytes("Updated ");
            fs.Write(newData, 0, newData.Length);
        }
    }
}

File.Create and File.OpenRead return FileStream objects for byte-level file operations. File.Open provides more control with FileMode and FileAccess parameters. Streams are ideal for large files or when you need precise control over reading/writing.

The example shows writing bytes to a file and reading them back. Flush ensures all buffered data is written to disk. Streams implement IDisposable, so they should be used in using statements for proper resource cleanup. This approach is more flexible than the high-level methods but requires more code.

File Encryption and Decryption

The File class provides methods for simple file encryption using the current user's credentials. This example demonstrates basic file encryption and decryption.

Program.cs
using System;
using System.IO;
using System.Security.AccessControl;

class Program
{
    static void Main()
    {
        string originalFile = "original.txt";
        string encryptedFile = "encrypted.txt";
        string decryptedFile = "decrypted.txt";
        
        File.WriteAllText(originalFile, "This is sensitive data that needs protection.");
        
        try
        {
            // Encrypt the file
            File.Encrypt(originalFile);
            Console.WriteLine("File encrypted successfully.");
            
            // Copy the encrypted file
            File.Copy(originalFile, encryptedFile);
            
            // Decrypt the original file
            File.Decrypt(originalFile);
            Console.WriteLine("File decrypted successfully.");
            
            // Verify by reading decrypted content
            string content = File.ReadAllText(originalFile);
            Console.WriteLine("Decrypted content: " + content);
        }
        catch (PlatformNotSupportedException)
        {
            Console.WriteLine("Encryption not supported on this platform.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

File.Encrypt and File.Decrypt use the Windows EFS (Encrypting File System) when available. Encryption is tied to the current user account - other users can't decrypt the file. These methods are only available on Windows platforms.

The example encrypts a file, copies it while encrypted, then decrypts the original. Note that encryption support depends on the file system and operating system. Always handle potential exceptions and provide fallback mechanisms for unsupported scenarios. For cross-platform applications, consider other encryption libraries.

Source

File Class Documentation

This tutorial covered various file operations in C# using the File class, including reading, writing, copying, moving, and encrypting files.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all C# tutorials.