C# File
last modified November 15, 2026
This tutorial explores file handling in C# with the File class.
It covers essential operations such as creating, reading, writing, copying,
moving, deleting, and appending files.
The File class in the System.IO namespace provides
static methods for common file operations. Many of them open a file, do their
work, and close the file in a single call. Others return a
FileStream, StreamReader, or
StreamWriter for more control.
For object-oriented file handling, .NET provides the FileInfo
class. A FileInfo object represents one file and caches its
properties, while File is a set of utility methods that take a
path in each call. The text methods of File use UTF-8 unless we
pass another encoding.
The words.txt file
This is a text file that we read in several examples. It is placed in the
project directory, which is the working directory when the program is started
with dotnet run. The examples that write data create their own
files, so words.txt stays unchanged.
sky blue cloud raisin tree falcon owl eagle rock water lake
C# File.Create
The File.Create method creates or overwrites a file at the
specified path. It returns a FileStream, which provides read and
write access to the file.
using System.Text;
var path = "data.txt";
using (FileStream fs = File.Create(path))
{
byte[] data = Encoding.UTF8.GetBytes("falcon\nribbon\ncloud\n");
fs.Write(data);
}
Console.WriteLine($"{new FileInfo(path).Length} bytes written");
Console.Write(File.ReadAllText(path));
The example creates a file and writes three words into it as raw bytes.
using (FileStream fs = File.Create(path))
We create the file and get a stream to it. The using block closes
the stream at its end, so the data is on disk before we read the file back.
byte[] data = Encoding.UTF8.GetBytes("falcon\nribbon\ncloud\n");
A FileStream works with bytes, so we encode the text with
Encoding.UTF8.GetBytes.
fs.Write(data);
The bytes are written to the file with Write.
$ dotnet run 20 bytes written falcon ribbon cloud
C# File.CreateText
The File.CreateText method creates or overwrites a file for
writing UTF-8 encoded text. It returns a StreamWriter.
var path = "data.txt";
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("falcon");
sw.WriteLine("sky");
sw.WriteLine("cloud");
}
Console.Write(File.ReadAllText(path));
The example creates a new file and writes three words with
WriteLine. The StreamWriter encodes the text and
adds the line terminators for us.
$ dotnet run falcon sky cloud
C# File.Copy
The File.Copy method copies an existing file to a new file. It
takes the source file and the destination file as parameters.
var sourcePath = "words.txt";
var destPath = "words_bck.txt";
File.Copy(sourcePath, destPath);
Console.WriteLine($"file copied: {File.Exists(destPath)}");
try
{
File.Copy(sourcePath, destPath);
}
catch (IOException e)
{
Console.WriteLine(e.Message.Replace(Environment.CurrentDirectory, "."));
}
File.Copy(sourcePath, destPath, true);
Console.WriteLine("file overwritten");
The example copies a text file, tries to copy it again, and finally overwrites the copy.
try
{
File.Copy(sourcePath, destPath);
}
catch (IOException e)
By default, File.Copy does not overwrite an existing file; it
throws an IOException. We replace the absolute path in the
message with a dot to keep the output short.
File.Copy(sourcePath, destPath, true);
The third parameter allows the method to overwrite the destination file.
$ dotnet run file copied: True The file './words_bck.txt' already exists. file overwritten
C# File.Move
The File.Move method moves a file to a new location. The same
method is used to rename a file.
File.Copy("words.txt", "data.txt", true);
File.Move("data.txt", "data2.txt");
Console.WriteLine(File.Exists("data.txt"));
Console.WriteLine(File.Exists("data2.txt"));
Directory.CreateDirectory("backup");
File.Move("data2.txt", Path.Combine("backup", "words.txt"), true);
Console.WriteLine(File.Exists(Path.Combine("backup", "words.txt")));
We make a copy of words.txt, rename it, and move it to a
subdirectory.
File.Move("data.txt", "data2.txt");
The file is renamed from data.txt to data2.txt.
Directory.CreateDirectory("backup");
File.Move("data2.txt", Path.Combine("backup", "words.txt"), true);
The destination directory must exist. The third parameter, available since .NET Core 3.0, allows overwriting an existing destination file; this lets us run the program repeatedly.
$ dotnet run False True True
C# File.Exists
The File.Exists method determines whether the specified file
exists.
string[] paths = ["words.txt", "words2.txt", "."];
foreach (var path in paths)
{
if (File.Exists(path))
{
Console.WriteLine($"{path}: the file exists");
}
else
{
Console.WriteLine($"{path}: the file does not exist");
}
}
We check three paths. File.Exists returns false for
a directory, such as the current directory .; we would use
Directory.Exists for it. The method also returns
false instead of throwing when the path is invalid or the caller
has no permission to read it.
$ dotnet run words.txt: the file exists words2.txt: the file does not exist .: the file does not exist
C# File.Delete
The File.Delete method deletes the specified file.
var path = "data.txt";
File.WriteAllText(path, "temporary data");
Console.WriteLine(File.Exists(path));
File.Delete(path);
Console.WriteLine(File.Exists(path));
File.Delete(path);
Console.WriteLine("no exception for a missing file");
The example creates a file and deletes it. Deleting a file which does not
exist is not an error; File.Delete throws only when the
directory in the path does not exist or the file cannot be deleted. Therefore,
we do not need to call File.Exists before deleting a file.
$ dotnet run True False no exception for a missing file
File times
The File.GetCreationTime, File.GetLastWriteTime,
and File.GetLastAccessTime methods return the time stamps of a
file. The corresponding Set methods change them.
var path = "data.txt";
File.WriteAllText(path, "an old file");
File.SetLastWriteTime(path, new DateTime(2024, 3, 15, 10, 30, 0));
DateTime created = File.GetCreationTime(path);
DateTime modified = File.GetLastWriteTime(path);
DateTime accessed = File.GetLastAccessTime(path);
Console.WriteLine($"Created: {created:yyyy-MM-dd HH:mm}");
Console.WriteLine($"Modified: {modified:yyyy-MM-dd HH:mm}");
Console.WriteLine($"Accessed: {accessed:yyyy-MM-dd HH:mm}");
TimeSpan age = DateTime.Now - modified;
Console.WriteLine($"Not modified for {age.Days} days");
The example creates a file, backdates its last write time, and prints all three time stamps.
File.SetLastWriteTime(path, new DateTime(2024, 3, 15, 10, 30, 0));
We set the modification time to a date in the past.
DateTime created = File.GetCreationTime(path);
On Windows, the creation time is stored by the file system. On Linux, it is not always available; .NET then returns the older of the last write time and the status change time. That is why the creation time in the output matches the date we have set.
TimeSpan age = DateTime.Now - modified;
Subtracting two dates gives a TimeSpan. The number of days
depends on the day the program runs.
$ dotnet run Created: 2024-03-15 10:30 Modified: 2024-03-15 10:30 Accessed: 2026-11-15 15:04 Not modified for 975 days
C# File.Open
The File.Open method opens a FileStream on the
specified path. Its overloads take a file mode (Open,
Create, CreateNew, Truncate,
Append, or OpenOrCreate), a file access
(Read, Write, or ReadWrite), and a
file share value, which specifies what access other streams get to the same
file while it is open.
using System.Text;
var path = "words.txt";
using FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);
byte[] buf = new byte[16];
int n;
int total = 0;
while ((n = fs.Read(buf, 0, buf.Length)) > 0)
{
total += n;
Console.Write(Encoding.UTF8.GetString(buf, 0, n));
}
Console.WriteLine($"{total} bytes read");
The example reads the contents of the words.txt file in blocks of
sixteen bytes.
using FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);
We open an existing file for reading.
while ((n = fs.Read(buf, 0, buf.Length)) > 0)
{
total += n;
Console.Write(Encoding.UTF8.GetString(buf, 0, n));
}
The Read method fills the buffer and returns the number of bytes
read; zero means the end of the file. We decode only the first
n bytes of the buffer, because the last block is not full.
Decoding fixed-size byte blocks works here because the file is plain ASCII; a
multi-byte UTF-8 character could be split between two blocks. For text, a
StreamReader is the better tool.
$ dotnet run sky blue cloud raisin tree falcon owl eagle rock water lake 60 bytes read
File modes
The FileMode enumeration determines what happens when the file
exists or does not exist.
var path = "data.txt";
try
{
using var fs = File.Open(path, FileMode.Open);
}
catch (FileNotFoundException e)
{
Console.WriteLine(e.Message.Replace(Environment.CurrentDirectory, "."));
}
using (var fs = File.Open(path, FileMode.CreateNew))
{
fs.Write("abc"u8);
}
try
{
using var fs = File.Open(path, FileMode.CreateNew);
}
catch (IOException e)
{
Console.WriteLine(e.Message.Replace(Environment.CurrentDirectory, "."));
}
using (var fs = File.Open(path, FileMode.Append))
{
fs.Write("def"u8);
}
Console.WriteLine(File.ReadAllText(path));
using (var fs = File.Open(path, FileMode.Truncate))
{
fs.Write("xyz"u8);
}
Console.WriteLine(File.ReadAllText(path));
File.Delete(path);
The example goes through four of the file modes.
using var fs = File.Open(path, FileMode.Open);
FileMode.Open requires an existing file; otherwise, a
FileNotFoundException is thrown.
using (var fs = File.Open(path, FileMode.CreateNew))
{
fs.Write("abc"u8);
}
FileMode.CreateNew creates a new file and fails with an
IOException if the file already exists. This makes it safe
against overwriting existing data. The u8 suffix creates a UTF-8
byte literal.
using (var fs = File.Open(path, FileMode.Append))
FileMode.Append opens the file and moves to its end.
using (var fs = File.Open(path, FileMode.Truncate))
FileMode.Truncate opens an existing file and cuts its size to
zero bytes.
$ dotnet run Could not find file './data.txt'. The file './data.txt' already exists. abcdef xyz
C# File.OpenRead
The File.OpenRead method opens an existing file for reading. It
is a shortcut for File.Open with FileMode.Open and
FileAccess.Read, and returns a read-only
FileStream.
var path = "words.txt";
using FileStream fs = File.OpenRead(path);
Console.WriteLine($"CanRead: {fs.CanRead}, CanWrite: {fs.CanWrite}");
Console.WriteLine($"Length: {fs.Length}");
byte[] buf = new byte[3];
fs.ReadExactly(buf);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(buf));
try
{
fs.WriteByte(65);
}
catch (NotSupportedException e)
{
Console.WriteLine(e.Message);
}
The example opens words.txt with File.OpenRead,
reads the first three bytes, and tries to write to the stream.
fs.ReadExactly(buf);
The ReadExactly method, available since .NET 7, reads exactly as
many bytes as the buffer holds, or throws an exception at the end of the
stream.
fs.WriteByte(65);
The stream does not support writing, so the call throws a
NotSupportedException.
$ dotnet run CanRead: True, CanWrite: False Length: 60 sky Stream does not support writing.
C# File.OpenText
The File.OpenText method opens an existing UTF-8 encoded text file
for reading. It returns a StreamReader.
var path = "words.txt";
using StreamReader sr = File.OpenText(path);
int n = 1;
while (sr.ReadLine() is { } line)
{
Console.Write($"{n}:{line} ");
n++;
}
Console.WriteLine();
The example reads the file line by line and prints the lines with their numbers.
while (sr.ReadLine() is { } line)
ReadLine returns null at the end of the file. The
property pattern { } matches any non-null value. The
StreamReader decodes the bytes for us.
$ dotnet run 1:sky 2:blue 3:cloud 4:raisin 5:tree 6:falcon 7:owl 8:eagle 9:rock 10:water 11:lake
C# File.OpenWrite
The File.OpenWrite method opens an existing file or creates a new
file for writing. It returns a FileStream with write access. It
uses FileMode.OpenOrCreate: an existing file is not truncated.
var path = "langs.txt";
File.WriteAllText(path, "Python\nJavaScript\nTypeScript\n");
using (FileStream fs = File.OpenWrite(path))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine("PHP");
sw.WriteLine("Dart");
}
Console.Write(File.ReadAllText(path));
Console.WriteLine("-------------------");
using (StreamWriter sw = new StreamWriter(path, false))
{
sw.WriteLine("PHP");
sw.WriteLine("Dart");
}
Console.Write(File.ReadAllText(path));
The example shows the pitfall of File.OpenWrite.
File.WriteAllText(path, "Python\nJavaScript\nTypeScript\n");
We first create a file with three lines.
using (FileStream fs = File.OpenWrite(path)) using (StreamWriter sw = new StreamWriter(fs))
We open the file with File.OpenWrite and write two shorter
lines. The new data overwrites the beginning of the file, and the rest of the
old content remains. The output shows the leftover vaScript and
TypeScript lines.
using (StreamWriter sw = new StreamWriter(path, false))
To replace the content, we use File.Create,
File.CreateText, or a StreamWriter whose second
parameter is false (do not append), which truncate the file.
$ dotnet run PHP Dart vaScript TypeScript ------------------- PHP Dart
C# File.ReadLines
The File.ReadLines method reads the lines of a text file lazily,
returning an IEnumerable<string>. Unlike
File.ReadAllLines, it does not load all lines into memory at once.
var path = "words.txt";
var lines = File.ReadLines(path);
foreach (var line in lines.Where(e => e.Length > 4))
{
Console.WriteLine(line);
}
Console.WriteLine("-------------------");
string? first = File.ReadLines(path).FirstOrDefault(e => e.StartsWith('r'));
Console.WriteLine(first);
The example filters the lines with LINQ.
foreach (var line in lines.Where(e => e.Length > 4))
The lines are read one by one as the loop asks for them. Only words longer than four characters are printed.
string? first = File.ReadLines(path).FirstOrDefault(e => e.StartsWith('r'));
FirstOrDefault stops at the first match, and the file is closed
without reading the remaining lines. This makes File.ReadLines
efficient for large files.
$ dotnet run cloud raisin falcon eagle water ------------------- raisin
C# File.ReadAllLines
The File.ReadAllLines method reads all lines of a text file into
a string[] array in a single operation. Since the whole file is
loaded into memory, it is suited for small and medium-sized files.
var path = "words.txt";
string[] lines = File.ReadAllLines(path);
Console.WriteLine($"The file has {lines.Length} lines");
Console.WriteLine($"First: {lines[0]}, last: {lines[^1]}");
Array.Sort(lines);
Console.WriteLine(string.Join(", ", lines));
With the lines in an array, we can get the count, access the lines by index, and sort them. The trailing newline of the last line does not produce an extra empty element.
$ dotnet run The file has 11 lines First: sky, last: lake blue, cloud, eagle, falcon, lake, owl, raisin, rock, sky, tree, water
C# File.ReadAllText
The File.ReadAllText method opens a text file, reads all its text
into a string, and closes the file. It should not be used for very large
files.
var path = "words.txt";
string text = File.ReadAllText(path);
Console.WriteLine($"{text.Length} characters");
Console.WriteLine($"{text.Count(c => c == '\n')} newlines");
Console.WriteLine(text.Replace('\n', ' '));
The example reads the whole file into a string. The string contains the newline characters; we count them and replace them with spaces.
$ dotnet run 60 characters 11 newlines sky blue cloud raisin tree falcon owl eagle rock water lake
C# File.ReadAllBytes
The File.ReadAllBytes method opens a file, reads its contents
into a byte array, and closes the file. It is used for binary files, but any
file can be read as bytes.
var path = "words.txt";
byte[] data = File.ReadAllBytes(path);
Console.WriteLine($"{data.Length} bytes");
foreach (var chunk in data.Chunk(16))
{
Console.WriteLine(string.Join(" ", chunk.Select(b => b.ToString("X2"))));
}
The example reads words.txt as bytes and prints them in
hexadecimal format, sixteen bytes per row. The 0A bytes are the
newline characters.
$ dotnet run 60 bytes 73 6B 79 0A 62 6C 75 65 0A 63 6C 6F 75 64 0A 72 61 69 73 69 6E 0A 74 72 65 65 0A 66 61 6C 63 6F 6E 0A 6F 77 6C 0A 65 61 67 6C 65 0A 72 6F 63 6B 0A 77 61 74 65 72 0A 6C 61 6B 65 0A
C# File.WriteAllText
The File.WriteAllText method creates a new file, writes the
contents to it, and closes the file. If the target file already exists, it is
overwritten.
var path = "data.txt"; string data = "sky\ncloud\nfalcon\nowl\ncrane\n"; File.WriteAllText(path, data); Console.Write(File.ReadAllText(path)); File.WriteAllText(path, "overwritten\n"); Console.Write(File.ReadAllText(path));
In the example, we write five words to a file with
File.WriteAllText. The second call replaces the whole content of
the file.
$ dotnet run sky cloud falcon owl crane overwritten
C# File.WriteAllLines
The File.WriteAllLines method creates a new file, writes a
collection of strings to it as lines, and closes the file. The
File.AppendAllLines method adds lines to the end of a file.
var path = "data.txt";
string[] data = ["sky", "cloud", "falcon", "hawk"];
File.WriteAllLines(path, data);
var squares = Enumerable.Range(1, 5).Select(n => $"{n} {n * n}");
File.AppendAllLines(path, squares);
Console.Write(File.ReadAllText(path));
In the example, we write an array of strings to a file and append the lines produced by a LINQ query.
var squares = Enumerable.Range(1, 5).Select(n => $"{n} {n * n}");
File.AppendAllLines(path, squares);
Both methods accept any IEnumerable<string>, not only
arrays. Each string is followed by the platform line terminator.
$ dotnet run sky cloud falcon hawk 1 1 2 4 3 9 4 16 5 25
C# File.WriteAllBytes
The File.WriteAllBytes method creates a new file, writes the
specified byte array to it, and closes the file.
var path = "data.bin";
byte[] data = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
File.WriteAllBytes(path, data);
byte[] read = File.ReadAllBytes(path);
Console.WriteLine($"{read.Length} bytes");
Console.WriteLine(Convert.ToHexString(read));
Console.WriteLine(read.SequenceEqual(data));
The example writes eight bytes to a file and reads them back.
byte[] data = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
These are the eight bytes of the PNG file signature, which every PNG image starts with.
Console.WriteLine(read.SequenceEqual(data));
We verify that the bytes read from the file are the same as the written ones.
$ dotnet run 8 bytes 89504E470D0A1A0A True
Appending to files
The File.AppendText method returns a StreamWriter
that appends UTF-8 text to a file. The File.AppendAllText and
File.AppendAllLines methods append a string or lines in one call.
All three create the file if it does not exist.
var path = "log.txt";
File.WriteAllText(path, "start\n");
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("first entry");
sw.WriteLine("second entry");
}
File.AppendAllText(path, "third entry\n");
File.AppendAllLines(path, ["fourth entry", "end"]);
Console.Write(File.ReadAllText(path));
The example appends entries to a log file in three different ways.
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("first entry");
sw.WriteLine("second entry");
}
File.AppendText is useful when we write several pieces of text
in a row.
File.AppendAllText(path, "third entry\n"); File.AppendAllLines(path, ["fourth entry", "end"]);
AppendAllText writes the string as it is, so we add the newline
ourselves. AppendAllLines adds a line terminator after each
string.
$ dotnet run start first entry second entry third entry fourth entry end
C# File.Replace
The File.Replace method replaces the contents of a file with the
contents of another file, deletes the source file, and optionally creates a
backup of the replaced file.
File.WriteAllText("config.txt", "version=1\n");
File.WriteAllText("config.new", "version=2\n");
File.Replace("config.new", "config.txt", "config.bak");
Console.Write($"config.txt: {File.ReadAllText("config.txt")}");
Console.Write($"config.bak: {File.ReadAllText("config.bak")}");
Console.WriteLine($"config.new exists: {File.Exists("config.new")}");
This is a common pattern for updating a file safely: the new version is written to a separate file first and then swapped in.
File.Replace("config.new", "config.txt", "config.bak");
The content of config.new replaces config.txt, the
old content is kept in config.bak, and config.new no
longer exists. If something goes wrong while writing the new file, the
original file is left untouched.
$ dotnet run config.txt: version=2 config.bak: version=1 config.new exists: False
C# File.SetAttributes and File.GetAttributes
The File.SetAttributes and File.GetAttributes
methods set and retrieve file attributes such as read-only or hidden.
var path = "data.txt";
File.WriteAllText(path, "important data");
Console.WriteLine($"Attributes: {File.GetAttributes(path)}");
File.SetAttributes(path, FileAttributes.ReadOnly);
Console.WriteLine($"Attributes: {File.GetAttributes(path)}");
try
{
File.WriteAllText(path, "new data");
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message.Replace(Environment.CurrentDirectory, "."));
}
File.SetAttributes(path, FileAttributes.Normal);
File.WriteAllText(path, "new data");
Console.WriteLine(File.ReadAllText(path));
The example makes a file read-only, tries to write to it, and then makes it writable again.
File.SetAttributes(path, FileAttributes.ReadOnly);
On Windows, this sets the read-only attribute. On Linux and macOS, .NET removes the write permissions of the file.
File.SetAttributes(path, FileAttributes.Normal);
FileAttributes.Normal clears the other attributes.
$ dotnet run Attributes: Normal Attributes: ReadOnly Access to the path './data.txt' is denied. new data
Unix file modes
Since .NET 7, the File.GetUnixFileMode and
File.SetUnixFileMode methods read and change the Unix
permissions of a file. They are not supported on Windows.
if (OperatingSystem.IsWindows())
{
Console.WriteLine("Unix file modes are not supported on Windows");
return;
}
var path = "script.sh";
File.WriteAllText(path, "#!/bin/sh\necho hello\n");
Console.WriteLine(File.GetUnixFileMode(path));
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite
| UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
Console.WriteLine(File.GetUnixFileMode(path));
The example creates a shell script and makes it executable for its owner.
if (OperatingSystem.IsWindows())
{
Console.WriteLine("Unix file modes are not supported on Windows");
return;
}
The platform check lets the code analyzer know that the following calls do not run on Windows.
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite
| UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
UnixFileMode is a flags enumeration. The combination corresponds
to the rwxr--r-- permissions, or 744 in octal notation. The
initial mode depends on the umask of the user.
$ dotnet run OtherRead, GroupWrite, GroupRead, UserWrite, UserRead OtherRead, GroupRead, UserExecute, UserWrite, UserRead
Asynchronous methods
Most reading and writing methods of the File class have
asynchronous versions, such as ReadAllTextAsync,
WriteAllLinesAsync, or ReadLinesAsync. They do not
block the calling thread while the data is read or written.
var path = "data.txt";
string[] words = ["sky", "cloud", "falcon", "hawk"];
await File.WriteAllLinesAsync(path, words);
string text = await File.ReadAllTextAsync(path);
Console.Write(text);
await foreach (var line in File.ReadLinesAsync(path))
{
Console.Write($"{line.ToUpper()} ");
}
Console.WriteLine();
The example writes and reads a file asynchronously.
await File.WriteAllLinesAsync(path, words);
The asynchronous methods return a Task, which we await.
await foreach (var line in File.ReadLinesAsync(path))
The File.ReadLinesAsync method, available since .NET 7, returns an
IAsyncEnumerable<string>, which is consumed with
await foreach.
$ dotnet run sky cloud falcon hawk SKY CLOUD FALCON HAWK
Source
File class - .NET API
Common I/O tasks
In this article we have worked with files in C# using the File
class of the System.IO namespace. We have created, copied, moved,
and deleted files, read and written text and bytes, appended data, and changed
file attributes. See also the C# FileInfo,
C# FileStream, and
C# read text file articles.
Author
List all C# tutorials.