C# File class
last modified November 6, 2026
In this article we show how to work with files using the File
class in C#.
File is a static class in the System.IO namespace.
Its methods create, read, write, copy, move, and delete files, and get or set
file metadata. Each method takes a path and opens and closes the file itself,
so most tasks take a single line of code. For many operations on the same file,
the FileInfo class or a FileStream is often a better
fit.
Each example creates a demo directory in the working directory and
deletes it at the end. The outputs come from Linux.
Checking whether a file exists
The File.Exists method tells whether a file exists.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "notes.txt");
Console.WriteLine($"exists: {File.Exists(path)}");
File.WriteAllText(path, "first note\n");
Console.WriteLine($"exists: {File.Exists(path)}");
Console.WriteLine($"directory: {File.Exists("demo")}");
Console.WriteLine($"null path: {File.Exists(null)}");
Directory.Delete("demo", true);
We check a path before and after creating the file.
Console.WriteLine($"directory: {File.Exists("demo")}");
Console.WriteLine($"null path: {File.Exists(null)}");
Exists returns false for a directory, and it never
throws: an invalid path, a null value, or a path we have no
permission to read also give false. The result can be out of date
as soon as it is returned, because another process may create or delete the
file. Code that opens a file should still handle exceptions.
$ dotnet run exists: False exists: True directory: False null path: False
Reading and writing text
The WriteAllText, AppendAllText,
ReadAllText, and their line-based variants handle whole text
files.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "words.txt");
File.WriteAllText(path, "sky\ncloud\n");
File.AppendAllText(path, "rain\n");
File.AppendAllLines(path, ["snow", "wind"]);
string content = File.ReadAllText(path);
Console.Write(content);
string[] lines = File.ReadAllLines(path);
Console.WriteLine($"{lines.Length} lines, last: {lines[^1]}");
File.WriteAllLines(path, lines.Order());
Console.WriteLine(string.Join(", ", File.ReadAllLines(path)));
Directory.Delete("demo", true);
We write, append, read, sort, and rewrite a file of words.
File.WriteAllText(path, "sky\ncloud\n"); File.AppendAllText(path, "rain\n"); File.AppendAllLines(path, ["snow", "wind"]);
WriteAllText creates the file or overwrites an existing one.
AppendAllText adds text at the end and creates the file if
needed. AppendAllLines writes each string followed by a line
terminator, which is \n on Unix and \r\n on Windows.
string[] lines = File.ReadAllLines(path);
ReadAllLines returns an array of lines without the line
terminators. It recognizes \n, \r\n, and
\r.
File.WriteAllLines(path, lines.Order());
WriteAllLines accepts any IEnumerable<string>,
here the sorted lines.
$ dotnet run sky cloud rain snow wind 5 lines, last: wind cloud, rain, sky, snow, wind
Reading large files line by line
The ReadAll methods load the whole file into memory.
File.ReadLines returns the lines lazily, one at a time.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "log.txt");
File.WriteAllLines(path, Enumerable.Range(1, 100_000)
.Select(i => $"{i} {(i % 25_000 == 0 ? "ERROR" : "INFO")} message {i}"));
foreach (string line in File.ReadLines(path).Where(l => l.Contains("ERROR")))
{
Console.WriteLine(line);
}
string? first = File.ReadLines(path).FirstOrDefault();
Console.WriteLine($"first line: {first}");
Directory.Delete("demo", true);
We generate a log of 100,000 lines and search it for errors.
foreach (string line in File.ReadLines(path).Where(l => l.Contains("ERROR")))
Only the current line is kept in memory, so this works for files of any size. The file stays open until the enumeration ends.
string? first = File.ReadLines(path).FirstOrDefault();
Because the reading is lazy, FirstOrDefault reads only the first
line and closes the file.
$ dotnet run 25000 ERROR message 25000 50000 ERROR message 50000 75000 ERROR message 75000 100000 ERROR message 100000 first line: 1 INFO message 1
Reading and writing bytes
Binary files are read and written as byte arrays.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "data.bin");
File.WriteAllBytes(path, [0xCA, 0xFE]);
File.AppendAllBytes(path, [0xBA, 0xBE]);
byte[] data = File.ReadAllBytes(path);
Console.WriteLine(Convert.ToHexString(data));
Console.WriteLine($"{data.Length} bytes");
Directory.Delete("demo", true);
We write two bytes, append two more, and print the content as a hexadecimal string.
File.AppendAllBytes(path, [0xBA, 0xBE]);
AppendAllBytes was added in .NET 9.
$ dotnet run CAFEBABE 4 bytes
Choosing an encoding
The text methods use UTF-8 without a byte order mark (BOM) by default. An
overload with an Encoding parameter selects another encoding.
using System.Text;
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "city.txt");
string text = "Ko\u0161ice";
File.WriteAllText(path, text);
Console.WriteLine($"UTF-8: {File.ReadAllBytes(path).Length} bytes");
File.WriteAllText(path, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
Console.WriteLine($"UTF-8 with BOM: {File.ReadAllBytes(path).Length} bytes");
File.WriteAllText(path, text, Encoding.Unicode);
Console.WriteLine($"UTF-16: {File.ReadAllBytes(path).Length} bytes");
Console.WriteLine(File.ReadAllText(path) == text);
Console.WriteLine(File.ReadAllText(path, Encoding.Latin1) == text);
Directory.Delete("demo", true);
We write the name of a Slovak city in three encodings and print the file size.
string text = "Ko\u0161ice";
The string has six characters; the letter š is written as a Unicode escape. The letter š takes two bytes in UTF-8, so the file has 7 bytes.
File.WriteAllText(path, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
With a BOM, three bytes are added at the start of the file. The static
Encoding.UTF8 property also emits the BOM.
Console.WriteLine(File.ReadAllText(path, Encoding.Latin1) == text);
The last file is in UTF-16 with a BOM. The reading methods detect a BOM and use the matching encoding, so the text is read correctly even though we pass Latin-1. The given encoding is used only for files without a BOM.
$ dotnet run UTF-8: 7 bytes UTF-8 with BOM: 10 bytes UTF-16: 14 bytes True True
Asynchronous methods
Most read and write methods have asynchronous versions that do not block the calling thread, which matters in GUI and server applications.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "colors.txt");
await File.WriteAllLinesAsync(path, ["red", "green", "blue"]);
await File.AppendAllTextAsync(path, "yellow\n");
string[] lines = await File.ReadAllLinesAsync(path);
Console.WriteLine(string.Join(" ", lines));
await foreach (string line in File.ReadLinesAsync(path))
{
Console.WriteLine(line.ToUpperInvariant());
}
Directory.Delete("demo", true);
We write, append, and read lines asynchronously.
await foreach (string line in File.ReadLinesAsync(path))
ReadLinesAsync, added in .NET 7, returns an
IAsyncEnumerable<string> that we consume with
await foreach.
$ dotnet run red green blue yellow RED GREEN BLUE YELLOW
Copying and moving files
File.Copy copies a file and File.Move moves or
renames it.
Directory.CreateDirectory("demo");
string source = Path.Combine("demo", "report.txt");
string copy = Path.Combine("demo", "report-copy.txt");
string moved = Path.Combine("demo", "archive.txt");
File.WriteAllText(source, "version 1");
File.Copy(source, copy);
File.WriteAllText(source, "version 2");
try
{
File.Copy(source, copy);
}
catch (IOException e)
{
Console.WriteLine($"IOException: {e.Message.Replace(Environment.CurrentDirectory, ".")}");
}
File.Copy(source, copy, overwrite: true);
Console.WriteLine($"copy: {File.ReadAllText(copy)}");
File.Move(copy, moved);
Console.WriteLine($"copy exists: {File.Exists(copy)}, archive exists: {File.Exists(moved)}");
File.Move(source, moved, overwrite: true);
Console.WriteLine(string.Join(", ", Directory.GetFiles("demo").Select(Path.GetFileName)));
Directory.Delete("demo", true);
We copy a file twice, then move the copy and move the source over it.
try
{
File.Copy(source, copy);
}
By default, neither method overwrites an existing file; they throw an
IOException instead.
File.Copy(source, copy, overwrite: true);
The overwrite parameter allows replacing the destination. For
File.Move it was added in .NET Core 3.0.
File.Move(source, moved, overwrite: true);
After the last move, only archive.txt is left, holding the
content of the source file.
$ dotnet run IOException: The file './demo/report-copy.txt' already exists. copy: version 2 copy exists: False, archive exists: True archive.txt
Deleting files
File.Delete removes a file.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "temp.txt");
File.WriteAllText(path, "temporary data");
File.Delete(path);
Console.WriteLine($"deleted, exists: {File.Exists(path)}");
File.Delete(path);
Console.WriteLine("deleting a missing file does not throw");
try
{
File.Delete(Path.Combine("demo", "nodir", "temp.txt"));
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("missing directory: DirectoryNotFoundException");
}
Directory.Delete("demo", true);
We delete a file, delete it again, and delete a file in a missing directory.
File.Delete(path);
Console.WriteLine("deleting a missing file does not throw");
Deleting a file that does not exist is not an error, so there is no need to
call Exists first.
catch (DirectoryNotFoundException)
If the directory of the file is missing, the method throws
DirectoryNotFoundException. It also throws an
IOException when the file is in use on Windows, and an
UnauthorizedAccessException when the path is a directory or we
lack permission.
$ dotnet run deleted, exists: False deleting a missing file does not throw missing directory: DirectoryNotFoundException
Timestamps, attributes, and permissions
The File class reads and sets the timestamps, attributes, and,
on Unix, the permissions of a file.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "config.txt");
File.WriteAllText(path, "port=8080");
File.SetLastWriteTime(path, new DateTime(2026, 1, 15, 10, 30, 0));
Console.WriteLine($"last write: {File.GetLastWriteTime(path):yyyy-MM-dd HH:mm}");
Console.WriteLine($"attributes: {File.GetAttributes(path)}");
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);
Console.WriteLine($"attributes: {File.GetAttributes(path)}");
if (!OperatingSystem.IsWindows())
{
Console.WriteLine($"mode: {File.GetUnixFileMode(path)}");
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
Console.WriteLine($"mode: {File.GetUnixFileMode(path)}");
}
Console.WriteLine($"attributes: {File.GetAttributes(path)}");
Directory.Delete("demo", true);
We set the modification time, make the file read-only, and then change its Unix permissions.
File.SetLastWriteTime(path, new DateTime(2026, 1, 15, 10, 30, 0));
There are getters and setters for the creation, last access, and last write time, in local time and in UTC.
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);
FileAttributes is a flags enumeration, so we combine values with
the | operator. On Unix, setting ReadOnly removes
the write permissions, as the next line of the output shows.
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
GetUnixFileMode and SetUnixFileMode were added in
.NET 7 and are not supported on Windows. Giving the owner write permission
makes the file writable again, so its attributes return to
Normal.
$ dotnet run last write: 2026-01-15 10:30 attributes: Normal attributes: ReadOnly mode: OtherRead, GroupRead, UserRead mode: UserWrite, UserRead attributes: Normal
Opening streams
For reading or writing in steps, the File class opens readers,
writers, and streams.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "journal.txt");
using (StreamWriter writer = File.CreateText(path))
{
writer.WriteLine("Monday: rain");
}
using (StreamWriter writer = File.AppendText(path))
{
writer.WriteLine("Tuesday: sun");
}
using (StreamReader reader = File.OpenText(path))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
{
Console.WriteLine($"{fs.Length} bytes, CanWrite: {fs.CanWrite}");
}
Directory.Delete("demo", true);
We create a text file, append to it, and read it line by line.
using (StreamWriter writer = File.CreateText(path))
CreateText creates or overwrites a file and returns a UTF-8
StreamWriter. AppendText returns a writer that adds
to the end, and OpenText returns a StreamReader.
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
File.Open returns a FileStream; the
FileMode and FileAccess arguments control how the
file is opened.
$ dotnet run Monday: rain Tuesday: sun 26 bytes, CanWrite: False
Replacing a file safely
When a program saves a file by overwriting it, a crash during the write leaves a damaged file. A safer approach writes a temporary file and then replaces the original.
Directory.CreateDirectory("demo");
string settings = Path.Combine("demo", "settings.txt");
string temp = Path.Combine("demo", "settings.tmp");
string backup = Path.Combine("demo", "settings.bak");
File.WriteAllText(settings, "theme=light");
File.WriteAllText(temp, "theme=dark");
File.Replace(temp, settings, backup);
Console.WriteLine($"settings: {File.ReadAllText(settings)}");
Console.WriteLine($"backup: {File.ReadAllText(backup)}");
Console.WriteLine($"temp exists: {File.Exists(temp)}");
Directory.Delete("demo", true);
We save new settings to a temporary file and swap it with the original.
File.Replace(temp, settings, backup);
File.Replace moves the temporary file to the place of the
original and keeps the old version as a backup. The third argument can be
null if no backup is needed. Both files must be on the same
volume.
$ dotnet run settings: theme=dark backup: theme=light temp exists: False
Symbolic links
Since .NET 6, the File class creates and resolves symbolic
links.
Directory.CreateDirectory("demo");
string target = Path.Combine("demo", "app-1.2.log");
string link = Path.Combine("demo", "app.log");
File.WriteAllText(target, "started");
try
{
File.CreateSymbolicLink(link, "app-1.2.log");
Console.WriteLine(File.ReadAllText(link));
FileSystemInfo? resolved = File.ResolveLinkTarget(link, returnFinalTarget: true);
Console.WriteLine($"{Path.GetFileName(link)} -> {resolved?.Name}");
Console.WriteLine(File.GetAttributes(link));
}
catch (IOException e)
{
Console.WriteLine($"cannot create link: {e.Message}");
}
Directory.Delete("demo", true);
We create a link pointing to a versioned log file and read the file through it.
File.CreateSymbolicLink(link, "app-1.2.log");
The target is relative to the directory of the link. On Windows, creating a
symbolic link requires administrator rights or Developer Mode; otherwise the
method throws an IOException.
FileSystemInfo? resolved = File.ResolveLinkTarget(link, returnFinalTarget: true);
ResolveLinkTarget returns the target, or null if the
path is not a link. With returnFinalTarget, it follows chains of
links to the end. A link has the ReparsePoint attribute.
$ dotnet run started app.log -> app-1.2.log ReparsePoint
Source
In this article we have worked with files using the File class
in C#.
Author
List all C# tutorials.