File Class

System.IO

Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in their creation.

Public Static Members

  • AppendAllBytes
    (string path, byte[] bytes)

    Appends the specified byte array to the file at the specified path.

  • AppendAllLines
    (string path, IEnumerable contents)

    Appends the specified lines to the file at the specified path, and then flushes the stream to the underlying storage.

  • Copy
    (string sourceFileName, string destinationFileName)

    Copies an existing file to a new location.

  • Create
    (string path)

    Creates or overwrites a file in the specified path.

  • Delete
    (string path)

    Deletes the specified file.

  • Exists
    (string path)

    Determines whether the specified file exists.

  • Move
    (string sourceFileName, string destinationFileName)

    Moves a specified file to a new location, allowing the specification of a new file name.

  • ReadAllBytes
    (string path)

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

  • ReadAllLines
    (string path)

    Opens a text file, reads all lines of the file, and then returns them as a string array.

  • ReadAllText
    (string path)

    Opens a text file, reads all lines of the file, and then returns them as a string.

  • WriteAllBytes
    (string path, byte[] bytes)

    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.

  • WriteAllLines
    (string path, IEnumerable contents)

    Creates a new file, writes a collection of strings to the file, and then closes the file.

  • WriteAllText
    (string path, string contents)

    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.

AppendAllBytes

static void AppendAllBytes(string path, byte[] bytes)

Appends the specified byte array to the file at the specified path. If the file does not exist, this method creates a file, writes the specified data to the file, and then closes the file.

Parameters

path:
string
The file to append to.
bytes:
byte[]
The bytes to write to the file.

Exceptions

ArgumentNullException: path is null.
ArgumentException: path is an empty string, contains only white space, or contains one or more invalid characters.
DirectoryNotFoundException: The specified path is invalid (for example, it is on an unmapped drive).
IOException: An I/O error occurred while opening the file.

Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string filePath = "myFile.bin";
        byte[] initialData = { 0x01, 0x02, 0x03 };
        byte[] appendData = { 0x04, 0x05 };

        // Create the file with initial data
        File.WriteAllBytes(filePath, initialData);

        // Append more data
        File.AppendAllBytes(filePath, appendData);

        Console.WriteLine($"Data appended to {filePath}.");

        // Clean up
        File.Delete(filePath);
    }
}
                    

AppendAllLines

static void AppendAllLines(string path, IEnumerable<string> contents)

Appends the specified lines to the file at the specified path, and then flushes the stream to the underlying storage. If the file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.

Parameters

path:
string
The file to append to.
contents:
IEnumerable<string>
The lines to append to the file.

This method appends each line, followed by a line terminator, to the file.
Example:

using System;
using System.IO;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string filePath = "myLog.txt";
        var logEntries = new List<string>
        {
            "Log entry 1",
            "Log entry 2"
        };

        // Create the file with initial entries
        File.WriteAllLines(filePath, logEntries);

        // Append new entries
        var newEntries = new List<string> { "Log entry 3", "Log entry 4" };
        File.AppendAllLines(filePath, newEntries);

        Console.WriteLine($"Lines appended to {filePath}.");

        // Clean up
        File.Delete(filePath);
    }
}
                    

Copy

static void Copy(string sourceFileName, string destinationFileName)

Copies an existing file to a new location.

Parameters

sourceFileName:
string
The path and name of the file to copy.
destinationFileName:
string
The path and name to which the copied file is to be moved.

If destinationFileName already exists, it will be overwritten.
Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string sourceFile = "original.txt";
        string destFile = "copy_of_original.txt";

        // Create a dummy source file
        File.WriteAllText(sourceFile, "This is the original file content.");

        // Copy the file
        File.Copy(sourceFile, destFile);

        Console.WriteLine($"File '{sourceFile}' copied to '{destFile}'.");

        // Clean up
        File.Delete(sourceFile);
        File.Delete(destFile);
    }
}
                    

Create

static FileStream Create(string path)

Creates or overwrites a file in the specified path.

Parameters

path:
string
The name of the file to create.

Returns

FileStream
A new FileStream object.

Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string filePath = "newFile.txt";

        // Create a new file
        using (FileStream fs = File.Create(filePath))
        {
            // You can write to the stream here if needed
            byte[] data = new byte[1024];
            fs.Write(data, 0, data.Length);
        }

        Console.WriteLine($"File '{filePath}' created.");

        // Clean up
        File.Delete(filePath);
    }
}
                    

Delete

static void Delete(string path)

Deletes the specified file.

Parameters

path:
string
The name of the file to be deleted.

Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string filePath = "tempFileToDelete.txt";

        // Create a file to delete
        File.WriteAllText(filePath, "This file will be deleted.");

        if (File.Exists(filePath))
        {
            File.Delete(filePath);
            Console.WriteLine($"File '{filePath}' deleted successfully.");
        }
        else
        {
            Console.WriteLine($"File '{filePath}' does not exist.");
        }
    }
}
                    

Exists

static bool Exists(string path)

Determines whether the specified file exists.

Parameters

path:
string
The file to check.

Returns

bool
true if the caller has the required permissions and path contains a file; otherwise, false. Also returns false if any path components of path are not valid. A call to Exists that returns false may be aസ്‌tentatious result. For example, a file that disappears between the time Exists is called and OpenFile is called.

Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string existingFile = "existing.txt";
        string nonExistingFile = "nonexistent.txt";

        // Create a dummy file
        File.WriteAllText(existingFile, "Hello!");

        if (File.Exists(existingFile))
        {
            Console.WriteLine($"File '{existingFile}' exists.");
        }
        else
        {
            Console.WriteLine($"File '{existingFile}' does not exist.");
        }

        if (File.Exists(nonExistingFile))
        {
            Console.WriteLine($"File '{nonExistingFile}' exists.");
        }
        else
        {
            Console.WriteLine($"File '{nonExistingFile}' does not exist.");
        }

        // Clean up
        File.Delete(existingFile);
    }
}
                    

Move

static void Move(string sourceFileName, string destinationFileName)

Moves a specified file to a new location, allowing the specification of a new file name.

Parameters

sourceFileName:
string
The path and name of the file to move.
destinationFileName:
string
The path and name to which the file is to be moved.

If the destination file already exists, it will be overwritten.
Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string sourceFile = "sourceToMove.txt";
        string destFile = "movedFile.txt";

        // Create a dummy source file
        File.WriteAllText(sourceFile, "This file will be moved.");

        // Move the file
        File.Move(sourceFile, destFile);

        Console.WriteLine($"File '{sourceFile}' moved to '{destFile}'.");

        // Verify and clean up
        if (!File.Exists(sourceFile) && File.Exists(destFile))
        {
            Console.WriteLine("Move operation successful.");
            File.Delete(destFile);
        }
        else
        {
            Console.WriteLine("Move operation failed.");
            if (File.Exists(sourceFile)) File.Delete(sourceFile);
            if (File.Exists(destFile)) File.Delete(destFile);
        }
    }
}
                    

ReadAllBytes

static byte[] ReadAllBytes(string path)

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

Parameters

path:
string
The file to read.

Returns

byte[]
A byte array containing the contents of the file.

Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string filePath = "data.bin";
        byte[] dataToWrite = { 0x0A, 0x0B, 0x0C, 0x0D };

        // Create a binary file
        File.WriteAllBytes(filePath, dataToWrite);

        // Read all bytes from the file
        byte[] readData = File.ReadAllBytes(filePath);

        Console.WriteLine($"Read {readData.Length} bytes from '{filePath}'.");
        for (int i = 0; i < readData.Length; i++)
        {
            Console.Write($"{readData[i]:X2} ");
        }
        Console.WriteLine();

        // Clean up
        File.Delete(filePath);
    }
}
                    

ReadAllLines

static string[] ReadAllLines(string path)

Opens a text file, reads all lines of the file, and then returns them as a string array.

Parameters

path:
string
The file to read.

Returns

string[]
A string array containing the lines of the file.

Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string filePath = "lines.txt";
        string[] linesToWrite = { "First line", "Second line", "Third line" };

        // Create a text file
        File.WriteAllLines(filePath, linesToWrite);

        // Read all lines from the file
        string[] readLines = File.ReadAllLines(filePath);

        Console.WriteLine($"Read {readLines.Length} lines from '{filePath}':");
        foreach (string line in readLines)
        {
            Console.WriteLine($"- {line}");
        }

        // Clean up
        File.Delete(filePath);
    }
}
                    

ReadAllText

static string ReadAllText(string path)

Opens a text file, reads all lines of the file, and then returns them as a string.

Parameters

path:
string
The file to read.

Returns

string
A string containing all lines of the file.

Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string filePath = "singleFile.txt";
        string contentToWrite = "This is the entire content of the file.\nIt spans multiple lines.";

        // Create a text file
        File.WriteAllText(filePath, contentToWrite);

        // Read all text from the file
        string fileContent = File.ReadAllText(filePath);

        Console.WriteLine($"Content of '{filePath}':");
        Console.WriteLine(fileContent);

        // Clean up
        File.Delete(filePath);
    }
}
                    

WriteAllBytes

static void WriteAllBytes(string path, byte[] bytes)

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.

Parameters

path:
string
The file to write to.
bytes:
byte[]
The bytes to write to the file.

Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string filePath = "output.bin";
        byte[] data = { 0xAA, 0xBB, 0xCC, 0xDD, 0xEE };

        // Write bytes to the file
        File.WriteAllBytes(filePath, data);

        Console.WriteLine($"Successfully wrote {data.Length} bytes to '{filePath}'.");

        // Clean up
        File.Delete(filePath);
    }
}
                    

WriteAllLines

static void WriteAllLines(string path, IEnumerable<string> contents)

Creates a new file, writes a collection of strings to the file, and then closes the file. Each string is written followed by a line terminator. If the target file already exists, it is overwritten.

Parameters

path:
string
The file to write to.
contents:
IEnumerable<string>
The lines to write to the file.

Example:

using System;
using System.IO;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string filePath = "lines_output.txt";
        var lines = new List<string>
        {
            "Line 1: Hello World",
            "Line 2: This is a test.",
            "Line 3: Another line of text."
        };

        // Write lines to the file
        File.WriteAllLines(filePath, lines);

        Console.WriteLine($"Successfully wrote {lines.Count} lines to '{filePath}'.");

        // Clean up
        File.Delete(filePath);
    }
}
                    

WriteAllText

static void WriteAllText(string path, string contents)

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.

Parameters

path:
string
The file to write to.
contents:
string
The string to write to the file.

Example:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string filePath = "output.txt";
        string textContent = "This is the text content for the file.\nIt can include newlines.";

        // Write text to the file
        File.WriteAllText(filePath, textContent);

        Console.WriteLine($"Successfully wrote text to '{filePath}'.");

        // Clean up
        File.Delete(filePath);
    }
}