C# Reference ยท Files and I/O
The File class
Reference for System.IO.File in C#: check, copy, move, replace and delete files, read attributes and timestamps, open streams, and avoid common exceptions.
System.IO.File is a static class with one-call helpers for working with a single file: test whether it exists, copy, move or delete it, read and write its contents, open a stream on it, and read or change its attributes and timestamps. Every method takes a path as a string, so there is no object to create or dispose.
For reading and writing whole files, see File.ReadAllText() and ReadLines() and File.WriteAllText() and AppendAllText(). This page covers the file-management methods. When you need the same information for many operations on one file, FileInfo is the instance-based alternative.
if (File.Exists("report.txt")) { File.Copy("report.txt", "report.bak", overwrite: true); }
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 static bool Exists(string? path); public static void Copy(string sourceFileName, string destFileName, bool overwrite = false); public static void Move(string sourceFileName, string destFileName, bool overwrite = false); public static void Delete(string path); public static void Replace(string sourceFileName, string destinationFileName, string? destinationBackupFileName); public static FileAttributes GetAttributes(string path); public static DateTime GetLastWriteTimeUtc(string path); public static FileStream Open(string path, FileMode mode); public static FileStream OpenRead(string path); public static FileStream OpenWrite(string path); public static StreamWriter CreateText(string path); public static FileStream Create(string path);
| Method | Description |
|---|---|
Exists(path) |
true only if the path names an existing file. Returns false for directories, null, empty strings, invalid paths and any error. |
Copy(src, dest, overwrite) |
Copies a file. Without overwrite an existing destination throws IOException. |
Move(src, dest, overwrite) |
Moves or renames a file, also across drives. The overwrite parameter exists since .NET Core 3.0. |
Delete(path) |
Deletes the file. A missing file is ignored, but a missing directory in the path throws. |
Replace(src, dest, backup) |
Replaces dest with src and optionally keeps the old dest as backup; pass null to skip the backup. |
Create, CreateText |
Create or truncate a file and return a FileStream or StreamWriter. |
Open, OpenRead, OpenWrite |
Open a FileStream; see FileStream. |
GetAttributes, SetAttributes, Get/SetCreationTimeUtc, Get/SetLastWriteTimeUtc, Get/SetLastAccessTimeUtc |
Metadata access. |
Returns: bool, a stream, or a metadata value as listed above.
Errors: FileNotFoundException (source missing), DirectoryNotFoundException (a folder in the path is missing), IOException (destination exists, file in use, disk errors), UnauthorizedAccessException (no permission, read-only target, or the path is a directory), ArgumentException or ArgumentNullException (empty or null path).
Usage notes
Existsfollowed by an action is a race. Another process can create or delete the file between the two calls. For "create only if missing", open withFileMode.CreateNewand catchIOException; for "read if present", catchFileNotFoundException.Existshides errors. It returnsfalsewhen you lack permission or the path is malformed, sofalsedoes not always mean "the file is absent".- Relative paths resolve against the current working directory (
Directory.GetCurrentDirectory()), which is not necessarily the folder of your program. Build absolute paths withPath. - Move is atomic only on the same volume. Across volumes .NET copies and then deletes. For safe saves, write to a temporary file in the target folder and then use
File.ReplaceorFile.Move(temp, target, overwrite: true). - Locked files throw
IOException. On Windows an open file cannot be deleted or overwritten; on Linux and macOS you can usually delete an open file. Dispose streams withusing. - Read-only flag. On Linux, setting
FileInfo.IsReadOnlyremoves the write permission bits, and writing then throwsUnauthorizedAccessException. - Prefer UTC timestamps (
GetLastWriteTimeUtc) for comparisons and caching. - Performance: each static call re-checks the file system. If you ask for several properties of one file, a single
FileInfois cheaper than repeatedFile.*calls. - Newer helpers:
File.ReadLinesAsyncandFile.AppendAllLinesAsyncexist for async code, andFile.OpenHandle(.NET 6+) gives low-levelSafeFileHandleaccess forRandomAccess.