ZetCode

C# FileInfo

last modified November 15, 2026

This article shows how to work with files in C# using the FileInfo class.

FileInfo from the System.IO namespace represents a single file. Its properties expose the file's name, size, attributes, and timestamps, and its methods create, open, copy, move, and delete the file.

.NET also has the static File class with similar functionality. File methods take a path in every call, which suits one-off operations. A FileInfo object keeps the path and caches the file's metadata, which suits code that queries or changes the same file several times. Methods such as DirectoryInfo.GetFiles also return FileInfo objects, so the metadata of whole directory listings is available without extra calls.

Member Description
Name, FullName, Extension File name, absolute path, and extension.
Directory, DirectoryName Parent directory as a DirectoryInfo or as a string.
Exists, Length Whether the file exists and its size in bytes.
IsReadOnly, Attributes, UnixFileMode Attributes and permissions.
CreateText, AppendText, OpenText Create a StreamWriter or StreamReader.
Open, OpenRead, OpenWrite Open a FileStream.
CopyTo, MoveTo, Delete Copy, move or rename, and delete the file.
Refresh Reloads the cached file state.

Every example creates the files it needs and deletes them at the end, so the programs can be run repeatedly in an empty project directory.

C# FileInfo properties

The first example prints the basic properties of a file.

Program.cs
File.WriteAllLines("words.txt", ["sky", "borrow", "war", "ocean", "cup"]);

var fi = new FileInfo("words.txt");

Console.WriteLine($"Name: {fi.Name}");
Console.WriteLine($"Extension: {fi.Extension}");
Console.WriteLine($"Full name: {fi.FullName}");
Console.WriteLine($"Directory name: {fi.DirectoryName}");
Console.WriteLine($"Exists: {fi.Exists}");
Console.WriteLine($"Length: {fi.Length} bytes");
Console.WriteLine($"Read-only: {fi.IsReadOnly}");
Console.WriteLine($"Attributes: {fi.Attributes}");
Console.WriteLine($"Last write: {fi.LastWriteTime:yyyy-MM-dd HH:mm}");

fi.Delete();

We write a small text file and inspect it with a FileInfo object.

var fi = new FileInfo("words.txt");

The constructor takes a relative or absolute path. Creating the object does not touch the file system and does not require the file to exist.

Console.WriteLine($"Full name: {fi.FullName}");
Console.WriteLine($"Directory name: {fi.DirectoryName}");

FullName is the absolute path, resolved against the current working directory. DirectoryName is the path of the parent directory.

Console.WriteLine($"Length: {fi.Length} bytes");

Length is the size of the file in bytes. Five words with five newline characters take 25 bytes.

fi.Delete();

At the end we delete the file.

$ dotnet run
Name: words.txt
Extension: .txt
Full name: /home/jano/csharp/fileinfo/words.txt
Directory name: /home/jano/csharp/fileinfo
Exists: True
Length: 25 bytes
Read-only: False
Attributes: Normal
Last write: 2026-11-15 16:12

C# FileInfo create and read text file

The CreateText method returns a StreamWriter that writes a new UTF-8 text file; an existing file is overwritten. The OpenText method returns a StreamReader for an existing text file.

Program.cs
var fi = new FileInfo("colours.txt");

using (StreamWriter sw = fi.CreateText())
{
    sw.WriteLine("red");
    sw.WriteLine("yellow");
    sw.WriteLine("white");
    sw.WriteLine("brown");
}

using (StreamReader sr = fi.OpenText())
{
    string? line;

    while ((line = sr.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

fi.Refresh();
Console.WriteLine($"{fi.Name} has {fi.Length} bytes");

fi.Delete();

We write four colours to a file and read them back line by line.

using (StreamWriter sw = fi.CreateText())
{
    sw.WriteLine("red");
    sw.WriteLine("yellow");
    sw.WriteLine("white");
    sw.WriteLine("brown");
}

The writer must be closed before the file is read, so we use a using block rather than a using declaration, which would keep the writer open until the end of the program.

while ((line = sr.ReadLine()) != null)
{
    Console.WriteLine(line);
}

ReadLine returns null at the end of the file.

fi.Refresh();
Console.WriteLine($"{fi.Name} has {fi.Length} bytes");

The object did not know the file before it was written. We call Refresh to load its current state; the next section explains why.

$ dotnet run
red
yellow
white
brown
colours.txt has 23 bytes

C# FileInfo cached state and Refresh

A FileInfo object reads the file's state the first time a property such as Exists or Length is accessed and caches it. Changes made to the file afterwards are not visible until Refresh is called. Methods of the object itself, such as Delete or MoveTo, update the cache.

Program.cs
var fi = new FileInfo("data.txt");
Console.WriteLine($"Exists: {fi.Exists}");

File.WriteAllText("data.txt", "an old falcon\n");
Console.WriteLine($"Exists after writing: {fi.Exists}");

fi.Refresh();
Console.WriteLine($"Exists after Refresh: {fi.Exists}, {fi.Length} bytes");

File.AppendAllText("data.txt", "a blue sky\n");
Console.WriteLine($"Length before Refresh: {fi.Length}");

fi.Refresh();
Console.WriteLine($"Length after Refresh: {fi.Length}");

fi.Delete();
Console.WriteLine($"Exists after Delete: {fi.Exists}");

We change a file behind the object's back and watch the cached values.

var fi = new FileInfo("data.txt");
Console.WriteLine($"Exists: {fi.Exists}");

File.WriteAllText("data.txt", "an old falcon\n");
Console.WriteLine($"Exists after writing: {fi.Exists}");

The first access to Exists caches False. The file is then created with the static File class, but the object still reports that it does not exist.

fi.Refresh();
Console.WriteLine($"Exists after Refresh: {fi.Exists}, {fi.Length} bytes");

After Refresh, the object sees the file and its size.

File.AppendAllText("data.txt", "a blue sky\n");
Console.WriteLine($"Length before Refresh: {fi.Length}");

The same applies to Length: the appended text is not reflected until the next Refresh.

fi.Delete();
Console.WriteLine($"Exists after Delete: {fi.Exists}");

Delete invalidates the cache, so Exists is correct without a refresh.

$ dotnet run
Exists: False
Exists after writing: False
Exists after Refresh: True, 14 bytes
Length before Refresh: 14
Length after Refresh: 25
Exists after Delete: False

C# FileInfo append text to file

The AppendText method returns a StreamWriter that appends to the file. If the file does not exist, it is created.

Program.cs
var fi = new FileInfo("log.txt");

for (int i = 1; i <= 3; i++)
{
    using StreamWriter sw = fi.AppendText();
    sw.WriteLine($"run {i} at {new DateTime(2026, 11, 15, 10, i, 0):HH:mm}");
}

Console.Write(File.ReadAllText(fi.FullName));

fi.Delete();

We append a line to a log file three times.

for (int i = 1; i <= 3; i++)
{
    using StreamWriter sw = fi.AppendText();
    sw.WriteLine($"run {i} at {new DateTime(2026, 11, 15, 10, i, 0):HH:mm}");
}

The using declaration closes the writer at the end of each iteration. The first call creates the file, the following calls add lines to it. The fixed dates stand in for DateTime.Now to keep the output reproducible.

$ dotnet run
run 1 at 10:01
run 2 at 10:02
run 3 at 10:03

C# FileInfo copy file

The CopyTo method copies the file to a new location and returns a FileInfo for the copy. By default it throws an IOException if the destination exists; the overwrite parameter replaces it.

Program.cs
File.WriteAllText("words.txt", "sky\nwar\ncup\n");
File.WriteAllText("backup.txt", "old content\n");

var fi = new FileInfo("words.txt");

try
{
    fi.CopyTo("backup.txt");
}
catch (IOException e)
{
    Console.WriteLine($"CopyTo failed: {e.Message}");
}

FileInfo copy = fi.CopyTo("backup.txt", overwrite: true);
Console.WriteLine($"Copied to {copy.Name}, {copy.Length} bytes");
Console.Write(File.ReadAllText(copy.FullName));

fi.Delete();
copy.Delete();

We copy words.txt over an existing backup file.

try
{
    fi.CopyTo("backup.txt");
}
catch (IOException e)
{
    Console.WriteLine($"CopyTo failed: {e.Message}");
}

The first attempt fails because backup.txt already exists.

FileInfo copy = fi.CopyTo("backup.txt", overwrite: true);
Console.WriteLine($"Copied to {copy.Name}, {copy.Length} bytes");

With overwrite: true the old content is replaced. We use the returned object to print the size of the copy.

$ dotnet run
CopyTo failed: The file '/home/jano/csharp/fileinfo/backup.txt' already exists.
Copied to backup.txt, 12 bytes
sky
war
cup

C# FileInfo rename and move file

The MoveTo method moves the file to a new path. When the directory stays the same, this renames the file. Unlike CopyTo, it updates the object itself, which then points to the new location.

Program.cs
Directory.CreateDirectory("archive");
File.WriteAllText("report.txt", "quarterly figures\n");

var fi = new FileInfo("report.txt");
Console.WriteLine($"Before: {Path.GetRelativePath(".", fi.FullName)}");

fi.MoveTo("report-2026.txt");
Console.WriteLine($"Renamed: {Path.GetRelativePath(".", fi.FullName)}");

fi.MoveTo(Path.Combine("archive", fi.Name));
Console.WriteLine($"Moved: {Path.GetRelativePath(".", fi.FullName)}");

Console.WriteLine($"report.txt exists: {File.Exists("report.txt")}");
Console.WriteLine($"Directory: {fi.Directory?.Name}");

Directory.Delete("archive", recursive: true);

We rename a report and then move it to the archive directory.

fi.MoveTo("report-2026.txt");
Console.WriteLine($"Renamed: {Path.GetRelativePath(".", fi.FullName)}");

After the call, FullName refers to the new file name. We print it relative to the current directory with Path.GetRelativePath.

fi.MoveTo(Path.Combine("archive", fi.Name));

The same object is moved again, this time into a subdirectory. The target directory must exist. MoveTo also has an overwrite parameter for replacing an existing destination file.

Console.WriteLine($"Directory: {fi.Directory?.Name}");

The Directory property returns the parent directory as a DirectoryInfo object. It is nullable because a root path has no parent.

$ dotnet run
Before: report.txt
Renamed: report-2026.txt
Moved: archive/report-2026.txt
report.txt exists: False
Directory: archive

C# FileInfo missing files

Some operations require the file to exist and some do not.

Program.cs
var fi = new FileInfo("missing.txt");

fi.Delete();
Console.WriteLine("Deleting a missing file is not an error");

try
{
    Console.WriteLine(fi.Length);
}
catch (FileNotFoundException e)
{
    Console.WriteLine($"Length failed: {e.Message}");
}

try
{
    using var sr = fi.OpenText();
}
catch (FileNotFoundException e)
{
    Console.WriteLine($"OpenText failed: {e.GetType().Name}");
}

We call several members on a file that does not exist.

fi.Delete();
Console.WriteLine("Deleting a missing file is not an error");

Delete does nothing if the file does not exist, so there is no need to check Exists first. It throws only if the file cannot be deleted, for example due to missing permissions.

try
{
    Console.WriteLine(fi.Length);
}
catch (FileNotFoundException e)
{
    Console.WriteLine($"Length failed: {e.Message}");
}

Length throws a FileNotFoundException for a missing file, and so does OpenText. A check of Exists before such calls is not reliable, because another process can delete the file in between; handling the exception is the robust approach.

$ dotnet run
Deleting a missing file is not an error
Length failed: Could not find file '/home/jano/csharp/fileinfo/missing.txt'.
OpenText failed: FileNotFoundException

C# FileInfo read-only files

The IsReadOnly property gets or sets the read-only state of a file. On Windows it maps to the read-only attribute; on Unix systems it removes or restores the write permissions.

Program.cs
File.WriteAllText("config.txt", "port=8080\n");

var fi = new FileInfo("config.txt");
fi.IsReadOnly = true;

Console.WriteLine($"Read-only: {fi.IsReadOnly}");
Console.WriteLine($"Attributes: {fi.Attributes}");

try
{
    using StreamWriter sw = fi.AppendText();
    sw.WriteLine("debug=true");
}
catch (UnauthorizedAccessException)
{
    Console.WriteLine("Cannot write to a read-only file");
}

fi.IsReadOnly = false;
using (StreamWriter sw = fi.AppendText())
{
    sw.WriteLine("debug=true");
}

Console.Write(File.ReadAllText(fi.FullName));
fi.Delete();

We make a configuration file read-only and try to append to it.

var fi = new FileInfo("config.txt");
fi.IsReadOnly = true;

Setting the property changes the file on disk immediately.

try
{
    using StreamWriter sw = fi.AppendText();
    sw.WriteLine("debug=true");
}
catch (UnauthorizedAccessException)
{
    Console.WriteLine("Cannot write to a read-only file");
}

Opening a read-only file for writing throws an UnauthorizedAccessException. We then clear the flag and the write succeeds. On Windows, a read-only file also cannot be deleted, so the flag must be cleared before Delete as well.

$ dotnet run
Read-only: True
Attributes: ReadOnly
Cannot write to a read-only file
port=8080
debug=true

C# FileInfo Open

The Open method returns a FileStream with the given FileMode and FileAccess; the OpenRead and OpenWrite methods are shortcuts for common combinations. A stream works with bytes, which suits binary files.

Program.cs
var fi = new FileInfo("numbers.bin");

using (FileStream fs = fi.Open(FileMode.Create, FileAccess.Write))
{
    for (byte i = 1; i <= 10; i++)
    {
        fs.WriteByte((byte)(i * i));
    }
}

fi.Refresh();
Console.WriteLine($"{fi.Name}: {fi.Length} bytes");

using (FileStream fs = fi.OpenRead())
{
    fs.Seek(5, SeekOrigin.Begin);
    Console.WriteLine($"Byte at position 5: {fs.ReadByte()}");
}

fi.Delete();

We write the squares of the numbers 1 to 10 as bytes and read one of them back.

using (FileStream fs = fi.Open(FileMode.Create, FileAccess.Write))

FileMode.Create creates a new file or truncates an existing one.

fs.Seek(5, SeekOrigin.Begin);
Console.WriteLine($"Byte at position 5: {fs.ReadByte()}");

We move to position 5, the sixth byte, which holds 6 × 6.

$ dotnet run
numbers.bin: 10 bytes
Byte at position 5: 36

C# FileInfo directory listing

The DirectoryInfo.GetFiles method returns an array of FileInfo objects whose properties are filled in from the directory listing.

Program.cs
var di = Directory.CreateDirectory("demo");

File.WriteAllText("demo/notes.txt", new string('n', 120));
File.WriteAllText("demo/data.csv", new string('d', 4500));
File.WriteAllText("demo/readme.md", new string('r', 800));
File.WriteAllText("demo/todo.txt", new string('t', 45));

FileInfo[] files = di.GetFiles();

foreach (FileInfo fi in files.OrderByDescending(f => f.Length))
{
    Console.WriteLine($"{fi.Name,-12} {fi.Length,6} bytes");
}

long total = files.Sum(f => f.Length);
Console.WriteLine($"Total: {total} bytes in {files.Length} files");

var txt = files.Where(f => f.Extension == ".txt").Select(f => f.Name).Order();
Console.WriteLine($"Text files: {string.Join(", ", txt)}");

di.Delete(recursive: true);

We list the files of a directory sorted by size, with LINQ.

foreach (FileInfo fi in files.OrderByDescending(f => f.Length))
{
    Console.WriteLine($"{fi.Name,-12} {fi.Length,6} bytes");
}

The files are sorted from the largest to the smallest. The alignment components of the interpolated string format the output into columns.

long total = files.Sum(f => f.Length);

We compute the total size of the files.

var txt = files.Where(f => f.Extension == ".txt").Select(f => f.Name).Order();

We filter the files by their extension. Note that Extension includes the dot.

$ dotnet run
data.csv       4500 bytes
readme.md       800 bytes
notes.txt       120 bytes
todo.txt         45 bytes
Total: 5465 bytes in 4 files
Text files: notes.txt, todo.txt

C# FileInfo UnixFileMode

The UnixFileMode property, available since .NET 7, gets and sets Unix permissions as a flags enumeration. It is not supported on Windows.

Program.cs
if (OperatingSystem.IsWindows())
{
    Console.WriteLine("Unix file modes are not supported on Windows");
    return;
}

File.WriteAllText("deploy.sh", "#!/bin/sh\necho deployed\n");

var fi = new FileInfo("deploy.sh");
Console.WriteLine($"Before: {fi.UnixFileMode}");

fi.UnixFileMode |= UnixFileMode.UserExecute | UnixFileMode.GroupExecute;

fi.Refresh();
Console.WriteLine($"After: {fi.UnixFileMode}");

fi.Delete();

We make a shell script executable, like chmod ug+x.

if (OperatingSystem.IsWindows())
{
    Console.WriteLine("Unix file modes are not supported on Windows");
    return;
}

The check also satisfies the platform compatibility analyzer, which warns about calls of Unix-only APIs.

fi.UnixFileMode |= UnixFileMode.UserExecute | UnixFileMode.GroupExecute;

We add the execute permission for the owner and the group with a bitwise OR. The initial permissions depend on the umask of the process; here new files get rw-rw-r--.

$ dotnet run
Before: OtherRead, GroupWrite, GroupRead, UserWrite, UserRead
After: OtherRead, GroupExecute, GroupWrite, GroupRead, UserExecute, UserWrite, UserRead

Source

FileInfo class - .NET API

In this article we have worked with files using the C# FileInfo class. See also the File, DirectoryInfo, Path, and FileStream tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.