File Class

Namespace: System.IO

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

Methods

See Also

AppendAllLines

AppendAllLines (string path, IEnumerable<string> contents)

Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified contents to the file, and then closes the file.

Parameters

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

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\MyFile.txt";
        var lines = new List<string>() { "This is the first line.", "This is the second line." };

        // Append the lines to the file.
        File.AppendAllLines(path, lines);

        // Append more lines.
        var moreLines = new List<string>() { "This is a third line.", "And a fourth." };
        File.AppendAllLines(path, moreLines);

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

AppendAllText

AppendAllText (string path, string contents)

Appends specified data to the end of the specified file. If the file does not exist, this method creates it.

Parameters

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\MyFile.txt";
        string textToAppend = "\nThis text will be appended.";

        // Append the text to the file.
        File.AppendAllText(path, textToAppend);

        Console.WriteLine($"Text appended to {path}");
    }
}

AppendText

AppendText (string path)

Opens a file or creates a new file to write UTF-8 encoded text to.

Parameters

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\MyFile.txt";

        // Open the file for appending text.
        using (StreamWriter sw = File.AppendText(path))
        {
            sw.WriteLine("Appending this line.");
            sw.WriteLine("And another one.");
        }

        Console.WriteLine($"Text appended to {path} using StreamWriter.");
    }
}

Copy

Copy (string sourceFileName, string destinationFileName)

Copies an existing file to a new location.

Parameters

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string sourcePath = @"C:\temp\Original.txt";
        string destinationPath = @"C:\temp\Copied.txt";

        // Create a dummy source file if it doesn't exist
        if (!File.Exists(sourcePath))
        {
            File.WriteAllText(sourcePath, "This is the content of the original file.");
        }

        // Copy the file.
        File.Copy(sourcePath, destinationPath);

        Console.WriteLine($"File copied from {sourcePath} to {destinationPath}");
    }
}

Create

Create (string path)

Creates or overwrites a file in the specified path. The current file is overwritten if the file exists, and a new file is created if the file does not exist.

Parameters

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\NewFile.txt";

        // Create a new file. If it exists, it will be overwritten.
        using (FileStream fs = File.Create(path))
        {
            // You can write to the file stream here if needed
            byte[] content = new byte[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; // "Hello"
            fs.Write(content, 0, content.Length);
        }

        Console.WriteLine($"File created or overwritten at {path}");
    }
}

Delete

Delete (string path)

Deletes the specified file.

Parameters

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\FileToDelete.txt";

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

        if (File.Exists(path))
        {
            // Delete the file.
            File.Delete(path);
            Console.WriteLine($"File deleted: {path}");
        }
        else
        {
            Console.WriteLine($"File not found: {path}");
        }
    }
}

Exists

Exists (string path)

Determines whether the specified file exists.

Parameters

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string existingFilePath = @"C:\temp\ExistingFile.txt";
        string nonExistingFilePath = @"C:\temp\NonExistentFile.txt";

        // Create a dummy file for testing existence
        File.WriteAllText(existingFilePath, "This file exists.");

        // Check if the file exists.
        bool exists = File.Exists(existingFilePath);
        Console.WriteLine($"Does '{existingFilePath}' exist? {exists}"); // Output: True

        exists = File.Exists(nonExistingFilePath);
        Console.WriteLine($"Does '{nonExistingFilePath}' exist? {exists}"); // Output: False

        // Clean up the dummy file
        if (File.Exists(existingFilePath))
        {
            File.Delete(existingFilePath);
        }
    }
}

ReadAllBytes

ReadAllBytes (string path)

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

Parameters

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\BinaryFile.bin";

        // Create a dummy binary file
        byte[] content = { 0x01, 0x02, 0x03, 0x04, 0x05 };
        File.WriteAllBytes(path, content);

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

        Console.WriteLine($"Read {fileBytes.Length} bytes from {path}.");
        foreach (byte b in fileBytes)
        {
            Console.Write($"{b:X2} "); // Print bytes in hex format
        }
        Console.WriteLine();

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

ReadAllLines

ReadAllLines (string path)

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

Parameters

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\LinesFile.txt";

        // Create a dummy text file with multiple lines
        string[] linesToWrite = { "Line 1", "Line 2", "Line 3" };
        File.WriteAllLines(path, linesToWrite);

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

        Console.WriteLine($"Read {fileLines.Length} lines from {path}.");
        foreach (string line in fileLines)
        {
            Console.WriteLine($"- {line}");
        }

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

ReadAllText

ReadAllText (string path)

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

Parameters

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\TextFile.txt";
        string textToWrite = "This is the entire content of the file.";

        // Create a dummy text file
        File.WriteAllText(path, textToWrite);

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

        Console.WriteLine($"Read content from {path}:");
        Console.WriteLine(fileContent);

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

WriteAllBytes

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

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\NewBinaryFile.bin";
        byte[] content = { 0xFF, 0xEE, 0xDD, 0xCC };

        // Write bytes to the file.
        File.WriteAllBytes(path, content);

        Console.WriteLine($"Wrote {content.Length} bytes to {path}");

        // Verify by reading back
        byte[] readBytes = File.ReadAllBytes(path);
        Console.WriteLine($"Read back {readBytes.Length} bytes:");
        foreach (byte b in readBytes)
        {
            Console.Write($"{b:X2} ");
        }
        Console.WriteLine();

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

WriteAllLines

WriteAllLines (string path, IEnumerable<string> contents)

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

Parameters

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

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\NewLinesFile.txt";
        var linesToWrite = new List<string>() { "First line written.", "Second line.", "Third and final." };

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

        Console.WriteLine($"Wrote {linesToWrite.Count} lines to {path}");

        // Verify by reading back
        string[] readLines = File.ReadAllLines(path);
        Console.WriteLine("Content:");
        foreach (string line in readLines)
        {
            Console.WriteLine($"- {line}");
        }

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

WriteAllText

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

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = @"C:\temp\NewTextFile.txt";
        string textToWrite = "This is the content that will be written to the new file.";

        // Write text to the file.
        File.WriteAllText(path, textToWrite);

        Console.WriteLine($"Wrote text to {path}");

        // Verify by reading back
        string readText = File.ReadAllText(path);
        Console.WriteLine("Content read back:");
        Console.WriteLine(readText);

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