Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

The FileInfo and DirectoryInfo classes

Reference for FileInfo and DirectoryInfo in C#: name, length, extension, timestamps, attributes, copy, move, delete, enumerate and when to prefer them over File and Directory.

FileInfo and DirectoryInfo are the object-based counterparts of the static File and Directory classes. You create one with a path, and then ask it for the name, size, extension, parent folder, attributes and timestamps, or call methods such as CopyTo, MoveTo, Delete, GetFiles and EnumerateDirectories.

Constructing a FileInfo does not touch the disk and does not need the file to exist. The object caches the file's metadata the first time you read it, so values such as Length do not change when the file changes unless you call Refresh(). This makes them efficient when you inspect several properties of one file, and it is the reason a directory listing can return FileInfo objects without a separate disk call for each size.

C#
var info = new FileInfo("report.csv");
Console.WriteLine($"{info.Name}: {info.Length} bytes");

Try it

C# Inspect a file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Walk a directory tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public sealed class FileInfo : FileSystemInfo
{
    public FileInfo(string fileName);
    public long Length { get; }
    public string? DirectoryName { get; }
    public DirectoryInfo? Directory { get; }
    public bool IsReadOnly { get; set; }
    public FileInfo CopyTo(string destFileName, bool overwrite);
    public void MoveTo(string destFileName, bool overwrite);
    public FileStream OpenRead();
    public StreamReader OpenText();
    public StreamWriter AppendText();
}

public sealed class DirectoryInfo : FileSystemInfo
{
    public DirectoryInfo(string path);
    public DirectoryInfo? Parent { get; }
    public DirectoryInfo Root { get; }
    public DirectoryInfo CreateSubdirectory(string path);
    public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption);
    public DirectoryInfo[] GetDirectories();
}

Members shared through FileSystemInfo:

Member Description
Name, FullName, Extension File name, absolute path, and extension including the dot.
Exists Whether it exists (cached until Refresh()). For a FileInfo it is false for a directory.
Attributes FileAttributes flags (ReadOnly, Hidden, Directory, Normal, ...).
CreationTimeUtc, LastWriteTimeUtc, LastAccessTimeUtc Timestamps; the non-UTC versions are in local time. Settable.
UnixFileMode Permission bits on Unix systems.
LinkTarget, ResolveLinkTarget() Information about symbolic links.
Refresh() Reloads the cached data.
Delete() Deletes the file or empty directory (Delete(true) on DirectoryInfo removes contents).

Errors: Length on a missing file throws FileNotFoundException. GetFiles and friends throw DirectoryNotFoundException for a missing folder. MoveTo and CopyTo throw IOException when the target exists and overwrite is false. A null path throws ArgumentNullException; an empty path throws ArgumentException.

Usage notes

  • Values are cached. Exists, Length and the timestamps are read once and kept. After the file changes, call Refresh() or create a new object. MoveTo and Delete refresh the object themselves; CopyTo leaves the original unchanged and returns a new FileInfo for the copy.
  • Construction is free; reads cost a system call. new FileInfo(path) never throws for a non-existent file, unlike Length.
  • Efficiency in listings. DirectoryInfo.EnumerateFiles() fetches size and timestamps along with the names, so it is cheaper than Directory.GetFiles() followed by new FileInfo(path).Length for every entry.
  • Use File.* for one-off actions (File.Delete(path)), and FileInfo when you read several properties or pass the file around as an object.
  • Directory tree walks need no recursion helper for simple cases: EnumerateFiles("*", SearchOption.AllDirectories) or an EnumerationOptions object. Sort the results; the order is operating-system dependent.
  • IsReadOnly is portable shorthand. Windows sets an attribute; on Unix it removes the write permission bits (and the process then fails with UnauthorizedAccessException when writing). Use UnixFileMode for finer control on Unix.
  • Time zones. Timestamps without Utc are local times, which is why ...Utc is preferred for comparisons and storage.
  • Symbolic links. LinkTarget tells you where a link points, and ResolveLinkTarget(returnFinalTarget: true) follows a chain of links to the end.
  • DirectoryInfo and the root. Parent of a root directory is null.