C# File

Beginner
8 min read
Updated: Nov 2026
3 examples
System.IO

Definition and Usage

In C#, File is a static class in the System.IO namespace. It gives you ready-made methods to save text with WriteAllText(), load it with ReadAllText(), check a file with Exists(), duplicate it with Copy(), and remove it with Delete().

Because it is static, you never write new File(). You call File.Method(path) and pass the file path each time. Add using System.IO; at the top of your file to use it. Text is saved as UTF-8 without a byte order mark unless you pick another encoding.

The File Methods index lists every method guide in this series. To work with folders, see C# Directory.

Practise only in a temp folder.

Methods such as WriteAllText replace an existing file, and Delete has no undo. Every example here builds a demo folder inside Path.GetTempPath() and deletes only that folder. Do the same while you learn.

C# Syntax

A safe first program with a temp file:

C#
using System;
using System.IO;

string path = Path.Combine(Path.GetTempPath(), "codetofun-demo.txt");

File.WriteAllText(path, "Hello");                // create or overwrite
string text = File.ReadAllText(path);            // "Hello"
Console.WriteLine(text);

File.Delete(path);                               // clean up

File vs FileInfo vs StreamReader and StreamWriter

Several classes in System.IO work with the content of a file. Pick the one that matches the job:

ClassWhat it isGood for
FileA static class. You pass the path to each method.Quick one-off jobs: read, write, copy, move, delete
FileInfoAn object that remembers one file.Many actions on one file, plus properties such as Name, Length, and Extension
StreamReader / StreamWriterObjects that keep a file open and read or write text in steps.Large files, line-by-line work, and many small writes. Wrap them in using
PathA static class that works only with text.Joining and splitting paths. It never touches the disk

Which Method Should I Use?

Start from what you want to do:

I want to...UseRemember
Save text to a fileWriteAllText()Creates the file or replaces it
Add text to the endAppendAllText()No newline is added for you
Read all the textReadAllText()Loads the whole file into memory
Read a big file line by lineReadLines()Lazy: one line at a time
Check that a file is thereExists()Returns false for folders and bad paths
Copy or rename a fileCopy(), Move()The destination must not exist unless you allow overwrite
Read or change when a file was changedGetLastWriteTime(), SetLastWriteTime()Utc versions avoid time-zone surprises

C# Examples

Example 1 — Write a File, Read It Back, and Delete It

A first program that works only inside a temp demo folder: save a small note, read it, check it, and clean up.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-hub");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string path = Path.Combine(root, "note.txt");
        File.WriteAllText(path, "Hello from File");

        Console.WriteLine(File.Exists(path));
        Console.WriteLine(File.ReadAllText(path));

        File.Delete(path);
        Console.WriteLine(File.Exists(path));

        Directory.Delete(root, true);
    }
}

How It Works

  1. A private demo path. Path.GetTempPath() plus a fixed name gives a folder that belongs to this lesson. The first if removes a leftover from an earlier run, and CreateDirectory makes the folder fresh.
  2. Save the note. File.WriteAllText creates note.txt and puts the text in it. It would overwrite the file if it were already there.
  3. Check and read. File.Exists prints True, and File.ReadAllText returns the whole text as one string.
  4. Clean up. File.Delete removes the file, so Exists prints False. Deleting the demo folder at the end leaves nothing behind.

Example 2 — File (Static) vs FileInfo (Object)

Do the same job twice: once with the static File class and once with a FileInfo object that remembers the file.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-compare");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string path = Path.Combine(root, "report.txt");
        File.WriteAllText(path, "12345");

        Console.WriteLine(File.Exists(path));
        Console.WriteLine(File.ReadAllText(path).Length);

        FileInfo info = new FileInfo(path);
        Console.WriteLine(info.Name);
        Console.WriteLine(info.Extension);
        Console.WriteLine(info.Length);

        info.Delete();
        Console.WriteLine(File.Exists(path));

        Directory.Delete(root, true);
    }
}

How It Works

  1. Static style. File.Exists(path) and File.ReadAllText(path) take the path every time. There is no object to create, and the result is the text itself.
  2. Object style. new FileInfo(path) stores the path once. After that, Name, Extension, and Length need no argument. Length is the size in bytes, and five ASCII characters take five bytes.
  3. Same file, same answers. Both styles look at the same file on disk, so the character count from File and the byte count from FileInfo agree here.
  4. Delete from either side. info.Delete() removes the file, and the static File.Exists then prints False. For one or two quick calls use File. For many calls on one file, FileInfo reads better.

Example 3 — Whole-File Methods vs StreamWriter and StreamReader

Write three lines with a StreamWriter, then read them two ways: all at once with File, and one by one with a StreamReader.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        string root = Path.Combine(Path.GetTempPath(), "codetofun-file-streams");
        if (Directory.Exists(root)) Directory.Delete(root, true);
        Directory.CreateDirectory(root);

        string path = Path.Combine(root, "names.txt");

        using (StreamWriter writer = new StreamWriter(path)) {
            writer.WriteLine("Ann");
            writer.WriteLine("Bob");
            writer.WriteLine("Cy");
        }

        string[] all = File.ReadAllLines(path);
        Console.WriteLine(all.Length);

        using (StreamReader reader = new StreamReader(path)) {
            string line;
            while ((line = reader.ReadLine()) != null) {
                Console.WriteLine(line.ToUpper());
            }
        }

        Directory.Delete(root, true);
    }
}

How It Works

  1. Writer in a using block. A StreamWriter keeps the file open while you call WriteLine three times. The using block closes it at the closing brace, which also flushes the text to disk.
  2. Read it all at once. File.ReadAllLines opens, reads, and closes the file in one call and gives a string[], so Length is 3. Short and simple for small files.
  3. Read it one line at a time. StreamReader.ReadLine returns null at the end of the file, which ends the while loop. Only one line is in memory at a time.
  4. Which to choose. Pick a File method when you want the whole content in one step. Pick a stream when the file is large, or when you write and read in many small steps.

Next: C# File Methods Index

After you know what the File class is for, open the method index for a full tutorial on each File API.

Start withWhy
WriteAllText()Save text to a file in one call
ReadAllLines()Read a file as an array of lines
Exists()Check whether a file is there
Delete()Remove a file, and learn what it does when the file is missing

Full list: C# File Methods index (/c-sharp/file/method).

Frequently Asked Questions

File is a static class in System.IO. It has methods to check, copy, move, and delete files, to read and write whole files in one call, to open streams, and to work with attributes and timestamps.
File is static: you pass the path each time. FileInfo is an object created with new FileInfo(path) that remembers one file and gives properties such as Name, Length, Extension, and Exists.
Use File.ReadAllText and File.WriteAllText for small files and quick jobs. Use StreamReader and StreamWriter when the file is large, or when you read or write in many small steps and want the file to stay open.
Yes. They use a demo folder inside Path.GetTempPath(), create everything first, and delete only what they made. WriteAllText and Delete have no undo, so never point them at a real file while you learn.
Open the C# File Methods index. It lists Exists, Copy, Move, Replace, Delete, the stream methods, the ReadAll and WriteAll families, attributes, encryption, and all timestamp methods.

Browse every File method

Open the methods index for categorized guides with examples and FAQs.

File Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful