C# FileInfo
last modified April 20, 2025
This tutorial explains how to use the FileInfo class in C# to get detailed information about files. FileInfo provides properties and methods for file manipulation and metadata access.
The FileInfo class provides instance methods for creating, copying, deleting, moving, and opening files. It helps in getting file properties like size, creation time, and attributes.
FileInfo is part of the System.IO namespace. Unlike the
static File class, FileInfo works with specific file instances. It
offers better performance for multiple operations on the same file.
Basic FileInfo Example
This example demonstrates how to create a FileInfo object and access basic file properties. We'll display information about a sample file.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
File.WriteAllText(filePath, "This is sample text.");
FileInfo fileInfo = new FileInfo(filePath);
Console.WriteLine($"File Name: {fileInfo.Name}");
Console.WriteLine($"Full Path: {fileInfo.FullName}");
Console.WriteLine($"Size (bytes): {fileInfo.Length}");
Console.WriteLine($"Created: {fileInfo.CreationTime}");
Console.WriteLine($"Last Modified: {fileInfo.LastWriteTime}");
Console.WriteLine($"Attributes: {fileInfo.Attributes}");
}
}
The program creates a sample file and then uses FileInfo to display its
properties. FileInfo provides detailed metadata about the file
without needing to open it. The Name property returns just the
file name, while FullName gives the complete path.
Length shows the file size in bytes, and the time-related
properties provide creation and modification timestamps. The
Attributes property returns flags indicating file characteristics
like read-only, hidden, or system file status.
Checking File Existence and Properties
FileInfo helps verify file existence and check specific properties before performing operations. This example demonstrates these capabilities.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "testfile.dat";
FileInfo fileInfo = new FileInfo(filePath);
Console.WriteLine($"File exists: {fileInfo.Exists}");
if (!fileInfo.Exists)
{
using (File.Create(filePath)) { }
Console.WriteLine("File created.");
}
Console.WriteLine($"Is read-only: {fileInfo.IsReadOnly}");
Console.WriteLine($"Extension: {fileInfo.Extension}");
Console.WriteLine($"Directory: {fileInfo.DirectoryName}");
}
}
The Exists property checks if the file is present. If not, we
create it. The IsReadOnly property indicates if the file has the
read-only attribute set. Extension returns the file extension,
and DirectoryName provides the full path of the containing
directory.
This example shows how to safely check file status before operations. The
File.Create method is used to create the file if it doesn't
exist. All properties automatically update after file creation.
Copying and Moving Files
FileInfo provides methods for copying and moving files. This example demonstrates file operations with proper error handling.
using System;
using System.IO;
class Program
{
static void Main()
{
string sourceFile = "original.txt";
string copyFile = "copy.txt";
string moveFile = "moved.txt";
File.WriteAllText(sourceFile, "Important content");
FileInfo fileInfo = new FileInfo(sourceFile);
try
{
// Copy the file
fileInfo.CopyTo(copyFile, overwrite: true);
Console.WriteLine("File copied successfully.");
// Move the file
fileInfo.MoveTo(moveFile);
Console.WriteLine("File moved successfully.");
// Verify operations
Console.WriteLine($"Original exists: {File.Exists(sourceFile)}");
Console.WriteLine($"Copy exists: {File.Exists(copyFile)}");
Console.WriteLine($"Moved exists: {File.Exists(moveFile)}");
}
catch (IOException ex)
{
Console.WriteLine($"File operation failed: {ex.Message}");
}
}
}
CopyTo creates a duplicate of the file, with an option to
overwrite existing files. MoveTo relocates the file to a new
location. Both methods throw IOException if operations fail.
The example includes proper error handling for file operations. After moving,
the original file no longer exists at its initial location. The
overwrite parameter in CopyTo prevents exceptions
when the target file exists.
File Deletion and Attributes
This example shows how to delete files and modify file attributes using FileInfo. We'll demonstrate changing the read-only attribute.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "tempfile.txt";
File.WriteAllText(filePath, "Temporary content");
FileInfo fileInfo = new FileInfo(filePath);
// Set file to read-only
fileInfo.Attributes |= FileAttributes.ReadOnly;
Console.WriteLine($"Is read-only: {fileInfo.IsReadOnly}");
try
{
// Attempt to delete (will fail)
fileInfo.Delete();
Console.WriteLine("File deleted.");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Cannot delete read-only file.");
// Remove read-only attribute
fileInfo.Attributes &= ~FileAttributes.ReadOnly;
fileInfo.Delete();
Console.WriteLine("Read-only removed and file deleted.");
}
}
}
The Attributes property allows modifying file characteristics. We
set the read-only flag using bitwise OR operation. Attempting to delete a
read-only file throws UnauthorizedAccessException.
After handling the exception, we remove the read-only attribute using bitwise
AND with the complement of FileAttributes.ReadOnly. The file can
then be successfully deleted with the Delete method.
File Information with Refresh
FileInfo caches file information. This example shows when to use the
Refresh method to get updated file details.
using System;
using System.IO;
using System.Threading;
class Program
{
static void Main()
{
string filePath = "dynamic.txt";
File.WriteAllText(filePath, "Initial content");
FileInfo fileInfo = new FileInfo(filePath);
Console.WriteLine($"Initial size: {fileInfo.Length} bytes");
// Simulate external file modification
Thread.Sleep(2000);
File.AppendAllText(filePath, "\nAdditional content");
// Display cached size (incorrect)
Console.WriteLine($"Cached size: {fileInfo.Length} bytes");
// Refresh and get current size
fileInfo.Refresh();
Console.WriteLine($"Refreshed size: {fileInfo.Length} bytes");
}
}
FileInfo properties are cached after the first access. If the file changes
externally, call Refresh to update the cached information. The
example shows how file size remains cached until explicitly refreshed.
After modifying the file externally, the Length property returns
the old value. Calling Refresh forces FileInfo to re-read the
file metadata from disk, providing accurate current information.
Directory Information with FileInfo
FileInfo provides access to directory information through its properties. This example explores directory-related functionality.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = Path.Combine("docs", "report.pdf");
Directory.CreateDirectory("docs");
File.WriteAllText(filePath, "PDF content");
FileInfo fileInfo = new FileInfo(filePath);
Console.WriteLine($"Directory: {fileInfo.DirectoryName}");
Console.WriteLine($"Directory Info:");
DirectoryInfo dirInfo = fileInfo.Directory;
Console.WriteLine($" Full Path: {dirInfo.FullName}");
Console.WriteLine($" Created: {dirInfo.CreationTime}");
Console.WriteLine($" Files Count: {dirInfo.GetFiles().Length}");
}
}
The DirectoryName property returns the full path of the containing
directory. The Directory property provides a
DirectoryInfo object for more detailed directory operations.
This example creates a nested directory structure and a file within it. The
DirectoryInfo object allows accessing directory properties and
listing files. The GetFiles method returns all files in the
directory.
File Stream Operations
FileInfo provides methods for creating file streams. This example demonstrates reading and writing using FileInfo stream methods.
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string filePath = "data.bin";
FileInfo fileInfo = new FileInfo(filePath);
// Write to file using FileInfo
using (FileStream fs = fileInfo.Create())
{
byte[] data = Encoding.UTF8.GetBytes("Binary data content");
fs.Write(data, 0, data.Length);
Console.WriteLine("File created and written.");
}
// Read from file using FileInfo
using (FileStream fs = fileInfo.OpenRead())
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string content = Encoding.UTF8.GetString(buffer);
Console.WriteLine($"File content: {content}");
}
}
}
The Create method returns a writable FileStream for
new files. OpenRead provides a read-only stream for existing
files. Both methods properly handle file resources when used with
using statements.
This example writes binary data to a file and reads it back. The
FileStream methods work with byte arrays, requiring encoding
for text data. FileInfo's stream methods offer more control than simple
File class methods.
Source
This tutorial covered using the FileInfo class in C# for file operations, including properties, copying, moving, attributes, and stream access.
Author
List all C# tutorials.