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.
var info = new FileInfo("report.csv"); Console.WriteLine($"{info.Name}: {info.Length} bytes");
Try it
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.
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
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,Lengthand the timestamps are read once and kept. After the file changes, callRefresh()or create a new object.MoveToandDeleterefresh the object themselves;CopyToleaves the original unchanged and returns a newFileInfofor the copy. - Construction is free; reads cost a system call.
new FileInfo(path)never throws for a non-existent file, unlikeLength. - Efficiency in listings.
DirectoryInfo.EnumerateFiles()fetches size and timestamps along with the names, so it is cheaper thanDirectory.GetFiles()followed bynew FileInfo(path).Lengthfor every entry. - Use
File.*for one-off actions (File.Delete(path)), andFileInfowhen 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 anEnumerationOptionsobject. Sort the results; the order is operating-system dependent. IsReadOnlyis portable shorthand. Windows sets an attribute; on Unix it removes the write permission bits (and the process then fails withUnauthorizedAccessExceptionwhen writing). UseUnixFileModefor finer control on Unix.- Time zones. Timestamps without
Utcare local times, which is why...Utcis preferred for comparisons and storage. - Symbolic links.
LinkTargettells you where a link points, andResolveLinkTarget(returnFinalTarget: true)follows a chain of links to the end. DirectoryInfoand the root.Parentof a root directory isnull.