C-SHARP - 5.3 File and FileInfo

The File and FileInfo classes from the System.IO namespace both let you work with files in C#. They offer identical functionality but follow two different approaches — it's worth understanding the nuance so you pick the right one for each situation.

The File class: a static approach

The File class exposes static methods: you call them directly without creating an instance. Ideal for a one-off operation on a file — checking it exists, a quick read, deleting it, copying it. Examples:

using System.IO;

if (File.Exists("data.txt"))
{
    string content = File.ReadAllText("data.txt");
    File.WriteAllText("backup.txt", content);
    File.Copy("data.txt", "data-copy.txt");
    File.Delete("old.txt");
}

The FileInfo class: an object-oriented approach

The FileInfo class represents a file as an object. You instantiate a FileInfo once by passing it the path, then call its instance methods. It's more performant than File when you're doing several operations on the same file, since FileInfo avoids re-checking existence and permissions on every call.

FileInfo file = new FileInfo("data.txt");
Console.WriteLine(file.Length);          // size in bytes
Console.WriteLine(file.CreationTime);    // creation date
file.CopyTo("data-copy.txt");
file.MoveTo("new-location.txt");
file.Delete();

Which class should you use?

File is better suited for a single action. FileInfo is preferable when you're chaining several accesses to the same file, or when you need detailed information (size, dates, attributes). The two work together in practice: you can check existence with File.Exists() then instantiate a FileInfo for the operations that follow.