The FileInfo
class in C# is a powerful tool for working with files in an object-oriented way. It allows you to easily manipulate files, get file metadata, and perform various file operations. In this guide, we will cover all the methods and properties of the FileInfo class with detailed examples, real-world use cases, and a comprehensive summary to help you understand how to efficiently use FileInfo
in your applications.
FileInfo
ClassThe FileInfo
class, part of the System.IO
namespace, provides a variety of methods and properties to work with files. Unlike the static File
class, FileInfo
operates in an object-oriented manner, which makes it more efficient for handling files when multiple operations need to be performed. This class is useful for getting information about files, such as size, creation time, and for performing operations like copying, moving, and deleting files.
FileInfo
PropertiesThe FileInfo
class offers several properties that provide information about a file. Below is a list of all the properties, along with examples and explanations.
FullName
FileInfo fileInfo = new FileInfo(@"C:\temp\example.txt");
Console.WriteLine(fileInfo.FullName); // Output: C:\temp\example.txt
Use Case: Useful when you need to display the full path of a file or log file locations.
Name
Console.WriteLine(fileInfo.Name); // Output: example.txt
Use Case: Retrieve just the name of a file without the full path.
Length
Console.WriteLine(fileInfo.Length); // Output: File size in bytes
Use Case: To display or check the size of a file, such as when enforcing file size limits.
Extension
Console.WriteLine(fileInfo.Extension); // Output: .txt
Use Case: Determine the file type and apply specific logic based on the extension.
Directory
DirectoryInfo
representing the directory of the file.DirectoryInfo dirInfo = fileInfo.Directory;
Console.WriteLine(dirInfo.FullName); // Output: Directory path
Use Case: Retrieve information about the directory that contains the file.
DirectoryName
Console.WriteLine(fileInfo.DirectoryName); // Output: C:\temp
Use Case: Useful when logging or for further operations related to the directory.
CreationTime
and CreationTimeUtc
Console.WriteLine(fileInfo.CreationTime); // Output: File creation time
LastAccessTime
and LastAccessTimeUtc
Console.WriteLine(fileInfo.LastAccessTime); // Output: Last access time
Use Case: Useful for monitoring file usage and determining if a file is stale.
LastWriteTime
and LastWriteTimeUtc
Console.WriteLine(fileInfo.LastWriteTime); // Output: Last write time
Attributes
Console.WriteLine(fileInfo.Attributes); // Output: File attributes
Use Case: Modify file attributes for permissions or make a file hidden.
The FileInfo class provides various methods to manipulate files. Here are some of the most important methods:
Create()
using (FileStream fs = fileInfo.Create())
{
// Write data to the file if needed
}
Use Case: Create new files, such as when initializing log files.
CopyTo(string destination, bool overwrite = false)
fileInfo.CopyTo(@"C:\temp\copy_example.txt", true);
Delete()
fileInfo.Delete();
Console.WriteLine("File deleted successfully.");
Use Case: Delete old or unnecessary files.
MoveTo(string destination)
fileInfo.MoveTo(@"C:\temp\new_location.txt");
Open(FileMode mode, FileAccess access, FileShare share)
using (FileStream fs = fileInfo.Open(FileMode.Open, FileAccess.Read))
{
// Read from the file
}
OpenRead()
using (FileStream fs = fileInfo.OpenRead())
{
// Read from the file
}
Use Case: Efficient way to read from files without modifying them.
OpenWrite()
using (FileStream fs = fileInfo.OpenWrite())
{
// Write to the file
}
Replace(string destinationFileName, string destinationBackupFileName)
fileInfo.Replace(@"C:\temp\file_to_replace.txt", @"C:\temp\backup.txt");
using System;
using System.IO;
class Program
{
static void Main()
{
FileInfo fileInfo = new FileInfo(@"C:\temp\example.txt");
if (!fileInfo.Exists)
{
using (FileStream fs = fileInfo.Create())
{
byte[] content = System.Text.Encoding.UTF8.GetBytes("Hello, FileInfo!");
fs.Write(content, 0, content.Length);
}
}
Console.WriteLine($"File Name: {fileInfo.Name}");
Console.WriteLine($"File Size: {fileInfo.Length} bytes");
Console.WriteLine($"Created On: {fileInfo.CreationTime}");
Console.WriteLine($"Last Accessed: {fileInfo.LastAccessTime}");
// Move file to a new location
string newPath = @"C:\temp\example_moved.txt";
fileInfo.MoveTo(newPath);
Console.WriteLine($"File moved to: {newPath}");
}
}
Let’s create a LogFileManager
that creates log files, appends log messages, and provides metadata for each log file.
using System;
using System.IO;
class LogFileManager
{
private FileInfo logFile;
public LogFileManager(string logFilePath)
{
logFile = new FileInfo(logFilePath);
if (!logFile.Exists)
{
using (FileStream fs = logFile.Create())
{
fs.Write(System.Text.Encoding.UTF8.GetBytes("Log File Created.\n"));
}
}
}
public void AppendLog(string message)
{
using (StreamWriter writer = logFile.AppendText())
{
writer.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}");
}
}
public void DisplayLogMetadata()
{
Console.WriteLine($"Log File: {logFile.Name}");
Console.WriteLine($"Size: {logFile.Length} bytes");
Console.WriteLine($"Created On: {logFile.CreationTime}");
Console.WriteLine($"Last Modified: {logFile.LastWriteTime}");
}
}
class Program
{
static void Main()
{
LogFileManager logManager = new LogFileManager(@"C:\temp\log.txt");
logManager.AppendLog("Application started.");
logManager.AppendLog("An event occurred.");
logManager.AppendLog("Application stopped.");
logManager.DisplayLogMetadata();
}
}
LogFileManager
Class:AppendLog
is used to add messages to the log file.DisplayLogMetadata
provides detailed information about the log file.Use Case: This is useful for logging application events or errors, allowing you to maintain a comprehensive activity log.
FileInfo
class is ideal for accessing metadata about a file, such as its name, size, creation time, and modification time.FileInfo
is more efficient than repeatedly using the File class.FileInfo
provides an object-oriented approach, which is beneficial for organizing and managing file operations cleanly.Create()
, CopyTo()
, MoveTo()
, and Delete()
make FileInfo
a versatile class for managing file system operations.The FileInfo
class in C# is a powerful and flexible tool for managing files in an object-oriented way. By using FileInfo
, you can easily perform file operations, gather metadata, and handle files efficiently. The class provides numerous properties and methods, such as Length
, CreationTime
, MoveTo()
, and Delete()
, which make it an essential part of file management in C#.
Whether you are developing a simple console application or a complex enterprise solution, understanding and using FileInfo
can help you manage files effectively, as demonstrated in the Log File Manager example. It is a versatile tool that simplifies many common file operations, making your code more readable and maintainable.