C# FileInfo
last modified November 6, 2026
In this article we show how to work with files using the
FileInfo class in C#.
FileInfo from the System.IO namespace represents a
single file. Unlike the static File class, it is an object created
for a path; its properties give the name, size, timestamps, and attributes of
the file, and its methods copy, move, delete, and open it. Creating a
FileInfo object does not access the disk and the file does not
have to exist.
FileInfo reads the file information once and caches it, which
makes it efficient when several properties of the same file are needed. The
DirectoryInfo.GetFiles method returns FileInfo
objects whose information was obtained during the directory listing.
The examples create a demo directory in the working directory and
delete it at the end. The outputs come from Linux.
File properties
The first example prints the properties of a file.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "report.final.txt");
File.WriteAllText(path, "quarterly results");
File.SetLastWriteTime(path, new DateTime(2026, 3, 31, 17, 45, 0));
var fi = new FileInfo(path);
Console.WriteLine($"Name: {fi.Name}");
Console.WriteLine($"Extension: {fi.Extension}");
Console.WriteLine($"FullName: {Relative(fi.FullName)}");
Console.WriteLine($"DirectoryName: {Relative(fi.DirectoryName!)}");
Console.WriteLine($"Directory: {fi.Directory!.Name}");
Console.WriteLine($"Exists: {fi.Exists}");
Console.WriteLine($"Length: {fi.Length}");
Console.WriteLine($"LastWriteTime: {fi.LastWriteTime:yyyy-MM-dd HH:mm}");
Console.WriteLine($"Attributes: {fi.Attributes}");
Console.WriteLine($"IsReadOnly: {fi.IsReadOnly}");
Directory.Delete("demo", true);
static string Relative(string path) => path.Replace(Environment.CurrentDirectory, ".");
We create a file, set its modification time, and print its properties.
Console.WriteLine($"Name: {fi.Name}");
Console.WriteLine($"Extension: {fi.Extension}");
Name is the file name with the extension.
Extension is the part after the last dot, including the dot.
Console.WriteLine($"FullName: {Relative(fi.FullName)}");
Console.WriteLine($"DirectoryName: {Relative(fi.DirectoryName!)}");
Console.WriteLine($"Directory: {fi.Directory!.Name}");
FullName is the absolute path. DirectoryName is the
path of the parent directory as a string and Directory is the
parent as a DirectoryInfo object. We replace the working directory
with a dot to keep the output short.
Console.WriteLine($"Length: {fi.Length}");
Length is the size of the file in bytes.
$ dotnet run Name: report.final.txt Extension: .txt FullName: ./demo/report.final.txt DirectoryName: ./demo Directory: demo Exists: True Length: 17 LastWriteTime: 2026-03-31 17:45 Attributes: Normal IsReadOnly: False
Missing files
A FileInfo object can be created for a file that does not
exist.
var fi = new FileInfo(Path.Combine("demo", "missing.txt"));
Console.WriteLine($"Name: {fi.Name}");
Console.WriteLine($"Exists: {fi.Exists}");
Console.WriteLine($"Attributes: {(int)fi.Attributes}");
Console.WriteLine($"LastWriteTimeUtc: {fi.LastWriteTimeUtc:yyyy-MM-dd}");
try
{
Console.WriteLine(fi.Length);
}
catch (FileNotFoundException)
{
Console.WriteLine("Length: FileNotFoundException");
}
We print the properties of a missing file.
Console.WriteLine($"Attributes: {(int)fi.Attributes}");
Console.WriteLine($"LastWriteTimeUtc: {fi.LastWriteTimeUtc:yyyy-MM-dd}");
The name-based properties work. Exists is false,
Attributes returns -1, and the timestamps return January 1, 1601.
Because -1 has all bits set, IsReadOnly returns
true for a missing file.
Console.WriteLine(fi.Length);
Length throws a FileNotFoundException. Check
Exists before reading the file information.
$ dotnet run Name: missing.txt Exists: False Attributes: -1 LastWriteTimeUtc: 1601-01-01 Length: FileNotFoundException
Cached information and Refresh
The information in a FileInfo object is read the first time a
property needs it. It does not change when the file changes.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "data.txt");
var fi = new FileInfo(path);
Console.WriteLine($"exists: {fi.Exists}");
File.WriteAllText(path, "abc");
Console.WriteLine($"after File.WriteAllText: exists {fi.Exists}");
fi.Refresh();
Console.WriteLine($"after Refresh: exists {fi.Exists}, length {fi.Length}");
File.AppendAllText(path, "defgh");
Console.WriteLine($"after append: length {fi.Length}");
fi.Refresh();
Console.WriteLine($"after Refresh: length {fi.Length}");
fi.Delete();
Console.WriteLine($"after fi.Delete: exists {fi.Exists}");
Directory.Delete("demo", true);
We create, extend, and delete a file and print the cached state after each step.
File.WriteAllText(path, "abc");
Console.WriteLine($"after File.WriteAllText: exists {fi.Exists}");
The file was created by another method, so the object still reports that it does not exist.
fi.Refresh();
Refresh reads the information again. The same applies to the
length after the file grows.
fi.Delete();
Console.WriteLine($"after fi.Delete: exists {fi.Exists}");
Operations done through the FileInfo object itself, such as
Delete or Create, update its state. Call
Refresh before reading properties of a file that other code or
other programs may have changed.
$ dotnet run exists: False after File.WriteAllText: exists False after Refresh: exists True, length 3 after append: length 3 after Refresh: length 8 after fi.Delete: exists False
Copying and moving
The CopyTo and MoveTo methods copy and move the
file.
Directory.CreateDirectory(Path.Combine("demo", "archive"));
string path = Path.Combine("demo", "notes.txt");
File.WriteAllText(path, "meeting notes");
var fi = new FileInfo(path);
FileInfo copy = fi.CopyTo(Path.Combine("demo", "notes-copy.txt"));
Console.WriteLine($"copy: {copy.Name}, {copy.Length} bytes");
fi.MoveTo(Path.Combine("demo", "archive", "notes-2026.txt"));
Console.WriteLine($"fi now points to: {fi.Directory!.Name}/{fi.Name}");
Console.WriteLine($"old path exists: {File.Exists(path)}");
copy.MoveTo(fi.FullName, overwrite: true);
Console.WriteLine($"files in archive: {fi.Directory.GetFiles().Length}");
Directory.Delete("demo", true);
We copy a file, move the original to a subdirectory, and move the copy over it.
FileInfo copy = fi.CopyTo(Path.Combine("demo", "notes-copy.txt"));
CopyTo returns a new FileInfo object for the
copy. It throws an IOException if the destination exists, unless
the overwrite argument is true.
fi.MoveTo(Path.Combine("demo", "archive", "notes-2026.txt"));
MoveTo changes the object itself: after the move, its
Name and FullName point to the new location.
copy.MoveTo(fi.FullName, overwrite: true);
With overwrite, the move replaces the existing file, so only one
file remains in the archive.
$ dotnet run copy: notes-copy.txt, 13 bytes fi now points to: archive/notes-2026.txt old path exists: False files in archive: 1
Read-only files
The IsReadOnly property gets or sets the read-only state of a
file.
Directory.CreateDirectory("demo");
string path = Path.Combine("demo", "license.txt");
File.WriteAllText(path, "MIT");
var fi = new FileInfo(path);
fi.IsReadOnly = true;
Console.WriteLine($"IsReadOnly: {fi.IsReadOnly}, Attributes: {fi.Attributes}");
try
{
File.AppendAllText(path, " changed");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("write: UnauthorizedAccessException");
}
try
{
fi.Delete();
Console.WriteLine("delete: succeeded");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("delete: UnauthorizedAccessException");
fi.IsReadOnly = false;
fi.Delete();
}
Directory.Delete("demo", true);
We make a file read-only and try to write to it and delete it.
fi.IsReadOnly = true;
Setting IsReadOnly sets the ReadOnly attribute. On
Unix, it removes the write permissions of the file.
fi.Delete();
Console.WriteLine("delete: succeeded");
Writing fails on all systems. Deleting differs: on Windows, a read-only file
cannot be deleted and Delete throws an
UnauthorizedAccessException, so the example clears the flag and
tries again. On Unix, deleting a file is controlled by the permissions of its
directory, so the read-only file is deleted.
$ dotnet run IsReadOnly: True, Attributes: ReadOnly write: UnauthorizedAccessException delete: succeeded
Opening streams
FileInfo has the same stream methods as the File
class.
Directory.CreateDirectory("demo");
var fi = new FileInfo(Path.Combine("demo", "todo.txt"));
using (StreamWriter writer = fi.CreateText())
{
writer.WriteLine("buy milk");
}
using (StreamWriter writer = fi.AppendText())
{
writer.WriteLine("call Peter");
}
using (StreamReader reader = fi.OpenText())
{
Console.Write(reader.ReadToEnd());
}
var options = new FileStreamOptions { Mode = FileMode.Open, Access = FileAccess.Read, BufferSize = 0 };
using (FileStream fs = fi.Open(options))
{
Console.WriteLine($"{fs.Length} bytes, CanWrite: {fs.CanWrite}");
}
Directory.Delete("demo", true);
We create a text file, append a line, and read the file.
var options = new FileStreamOptions { Mode = FileMode.Open, Access = FileAccess.Read, BufferSize = 0 };
FileStreamOptions, added in .NET 6, collects all settings of a
stream in one object. A BufferSize of 0 turns off the buffering of
FileStream, which is useful when the caller does its own
buffering.
using (FileStream fs = fi.Open(options))
The Open method accepts the options object, as do the
FileStream constructor and File.Open.
$ dotnet run buy milk call Peter 20 bytes, CanWrite: False
Listing files with their sizes
DirectoryInfo.GetFiles returns FileInfo objects,
which LINQ queries can sort and group.
Directory.CreateDirectory("demo");
File.WriteAllText(Path.Combine("demo", "a.txt"), new string('a', 1200));
File.WriteAllText(Path.Combine("demo", "b.log"), new string('b', 30));
File.WriteAllText(Path.Combine("demo", "c.txt"), new string('c', 450));
File.WriteAllText(Path.Combine("demo", "d.csv"), new string('d', 7800));
var dir = new DirectoryInfo("demo");
FileInfo[] files = dir.GetFiles();
foreach (FileInfo f in files.OrderByDescending(f => f.Length))
{
Console.WriteLine($"{f.Name,-6} {f.Length,6}");
}
Console.WriteLine($"total: {files.Sum(f => f.Length)} bytes");
foreach (var g in files.GroupBy(f => f.Extension).OrderBy(g => g.Key))
{
Console.WriteLine($"{g.Key}: {g.Count()} files, {g.Sum(f => f.Length)} bytes");
}
Directory.Delete("demo", true);
We create four files and list them by size, then sum the sizes per extension.
foreach (FileInfo f in files.OrderByDescending(f => f.Length))
The size of each file is part of the listing, so reading Length
does not access the disk again.
foreach (var g in files.GroupBy(f => f.Extension).OrderBy(g => g.Key))
We group the files by extension and print the count and total size of each group.
$ dotnet run d.csv 7800 a.txt 1200 c.txt 450 b.log 30 total: 9480 bytes .csv: 1 files, 7800 bytes .log: 1 files, 30 bytes .txt: 2 files, 1650 bytes
Source
In this article we have worked with files using the FileInfo
class in C#.
Author
List all C# tutorials.