FileInfo Class
Represents a file.
Overview
The FileInfo
class provides properties and methods for accessing information about a file and for opening or creating files. It is an instance-based class, meaning you create an instance of FileInfo
to represent a specific file.
This class is useful for retrieving file attributes such as size, creation time, modification time, and for performing operations like deleting, moving, or copying the file. For static operations that don't require an instance, consider using the static members of the File
class.
Members
Constructor FileInfo(string fileName)
Initializes a new instance of the FileInfo
class with the specified path to the file.
Parameters
fileName
: The path to the file this instance represents.
Property long Length
Gets the size, in bytes, of the current file.
Returns
- The size of the current file in bytes.
Property string FullName
Gets the fully qualified path that the current file belongs to.
Returns
- The fully qualified name of the file.
Property DateTime CreationTime
Gets the creation time of the current file.
Returns
- A
DateTime
structure that contains the date and time the current file was created.
Property DateTime LastWriteTime
Gets the date and time the current file was last written to.
Returns
- A
DateTime
structure that contains the date and time the current file was last written to.
Method FileStream Create()
Creates or overwrites a file in the specified path.
Returns
- A new
FileStream
object that provides read/write access to the file.
Method void Delete()
Deletes the current file.
Method void MoveTo(string destFileName)
Moves the current file to a different location.
Parameters
destFileName
: The name of the destination location and file name.
Example
C# Example
using System;
using System.IO;
public class FileInfoExample
{
public static void Main(string[] args)
{
string filePath = "myDocument.txt";
// Create a dummy file for demonstration
File.WriteAllText(filePath, "This is a sample file for FileInfo demonstration.");
try
{
// Create a FileInfo object
FileInfo fileInfo = new FileInfo(filePath);
// Display file properties
Console.WriteLine($"File Name: {fileInfo.Name}");
Console.WriteLine($"Full Path: {fileInfo.FullName}");
Console.WriteLine($"Size: {fileInfo.Length} bytes");
Console.WriteLine($"Creation Time: {fileInfo.CreationTime}");
Console.WriteLine($"Last Write Time: {fileInfo.LastWriteTime}");
// Example of deleting the file
// Console.WriteLine($"Deleting file: {filePath}");
// fileInfo.Delete();
// Console.WriteLine("File deleted.");
}
catch (FileNotFoundException)
{
Console.WriteLine($"Error: The file '{filePath}' was not found.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Clean up the dummy file if it exists
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
}