System.IO.File Class

System.IO
Namespace: System.IO
Assembly: System.IO.dll

Represents a file, which is a collection of bytes in the storage medium.

Summary

The System.IO.File class provides static methods for the creation, copying, deletion, moving, and opening of files, and provides objects that enable you to read from and write to a file.

This class is designed to be used with file paths, which are strings representing the location of a file. It offers convenient methods for common file operations without needing to explicitly create or manage FileStream objects in many cases.

Note: This class is a wrapper around core file operations. For more advanced scenarios involving fine-grained control over file streams (like buffering, seeking, or specific encoding), consider using System.IO.FileStream directly.

Methods

AppendAllText

Show Overloads

Method Overloads

Appends the specified string to the file, or creates the file, writing the specified string to it. If the file already exists, lines are appended to the end of the file.


public static void AppendAllText (string path, string contents);
public static void AppendAllText (string path, string contents, System.Text.Encoding encoding);
public static void AppendAllText (string path, ReadOnlySpan<char> contents, System.Text.Encoding encoding = null);
public static System.Threading.Tasks.Task AppendAllTextAsync (string path, string contents, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task AppendAllTextAsync (string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
                
Parameters:

Copy

Show Overloads

Method Overloads

Copies an existing file to a new location.


public static void Copy (string sourceFileName, string destFileName);
public static void Copy (string sourceFileName, string destFileName, bool overwrite);
                
Parameters:

Delete

Show Overloads

Method Overloads

Deletes the specified file.


public static void Delete (string path);
                
Parameters:

Exists

Show Overloads

Method Overloads

Determines whether the specified file exists.


public static bool Exists (string path);
                
Parameters:
Returns:

true if the caller has the required permissions and path contains a file; otherwise, false. This method also returns false if path is null, an invalid path, or a zero-length string. If the caller does not have sufficient storage permissions to access the file, an UnauthorizedAccessException is thrown. If path specifies a directory, this method returns false.

Move

Show Overloads

Method Overloads

Moves a specified file to a new location, with options to handle file replacement.


public static void Move (string sourceFileName, string destFileName);
                
Parameters:

ReadAllBytes

Show Overloads

Method Overloads

Opens a binary file, reads the contents of the file into a byte array, and then closes the file.


public static byte[] ReadAllBytes (string path);
public static System.Threading.Tasks.Task<byte[]> ReadAllBytesAsync (string path, System.Threading.CancellationToken cancellationToken = default);
                
Parameters:
Returns:

A byte array containing the contents of the file.

ReadAllLines

Show Overloads

Method Overloads

Opens a text file, reads all lines of the file into a string array, and then closes the file.


public static string[] ReadAllLines (string path);
public static string[] ReadAllLines (string path, System.Text.Encoding encoding);
public static System.Threading.Tasks.Task<string[]> ReadAllLinesAsync (string path, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task<string[]> ReadAllLinesAsync (string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
                
Parameters:
Returns:

A string array containing the lines of the file.

ReadAllText

Show Overloads

Method Overloads

Opens a text file, reads all lines of the file into a string, and then closes the file.


public static string ReadAllText (string path);
public static string ReadAllText (string path, System.Text.Encoding encoding);
public static System.Threading.Tasks.Task<string> ReadAllTextAsync (string path, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task<string> ReadAllTextAsync (string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
                
Parameters:
Returns:

A string containing all lines of the file.

WriteAllBytes

Show Overloads

Method Overloads

Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.


public static void WriteAllBytes (string path, byte[] bytes);
public static System.Threading.Tasks.Task WriteAllBytesAsync (string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default);
                
Parameters:

WriteAllLines

Show Overloads

Method Overloads

Creates a new file, writes a collection of strings to the file, and then closes the file. Each string corresponds to a line in the file.


public static void WriteAllLines (string path, string[] contents);
public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<string> contents);
public static void WriteAllLines (string path, string[] contents, System.Text.Encoding encoding);
public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<string> contents, System.Text.Encoding encoding);
public static System.Threading.Tasks.Task WriteAllLinesAsync (string path, string[] contents, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task WriteAllLinesAsync (string path, System.Collections.Generic.IEnumerable<string> contents, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task WriteAllLinesAsync (string path, string[] contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task WriteAllLinesAsync (string path, System.Collections.Generic.IEnumerable<string> contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
                
Parameters:

WriteAllText

Show Overloads

Method Overloads

Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.


public static void WriteAllText (string path, string contents);
public static void WriteAllText (string path, string contents, System.Text.Encoding encoding);
public static System.Threading.Tasks.Task WriteAllTextAsync (string path, string contents, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task WriteAllTextAsync (string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
                
Parameters:

Remarks

The File class provides a convenient, high-level interface for file manipulation. It handles the underlying stream operations, buffering, and error handling for you, making common tasks simpler.

All methods in the File class that perform file operations perform them synchronously by default, unless an asynchronous overload (e.g., `ReadAllBytesAsync`) is explicitly called.

Example

Writing and Reading a Text File


using System;
using System.IO;

public class FileExample
{
    public static void Main(string[] args)
    {
        string filePath = "my_document.txt";
        string content = "Hello, world!\nThis is a sample text file.";

        try
        {
            // Write content to the file
            File.WriteAllText(filePath, content);
            Console.WriteLine($"Content written to {filePath}");

            // Read content from the file
            string readContent = File.ReadAllText(filePath);
            Console.WriteLine($"\nContent read from {filePath}:");
            Console.WriteLine(readContent);

            // Append to the file
            File.AppendAllText(filePath, "\nAppending a new line.");
            Console.WriteLine($"\nContent appended to {filePath}");

            // Read all lines
            string[] lines = File.ReadAllLines(filePath);
            Console.WriteLine("\nLines in the file:");
            foreach (string line in lines)
            {
                Console.WriteLine($"- {line}");
            }

            // Check if file exists
            if (File.Exists(filePath))
            {
                Console.WriteLine($"\nFile '{filePath}' exists.");
            }

            // Copy the file
            string copyPath = "my_document_copy.txt";
            File.Copy(filePath, copyPath, true);
            Console.WriteLine($"File copied to '{copyPath}'.");

            // Delete the original file
            File.Delete(filePath);
            Console.WriteLine($"Original file '{filePath}' deleted.");

            // Move the copied file
            string movePath = "moved_document.txt";
            File.Move(copyPath, movePath);
            Console.WriteLine($"File '{copyPath}' moved to '{movePath}'.");
        }
        catch (IOException ex)
        {
            Console.WriteLine($"An IO error occurred: {ex.Message}");
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine($"Permission error: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}
                

See Also