FileInfo Class
Namespace: System.IO
public sealed class FileInfo : FileSystemInfo
Summary:
Represents a file in a directory.
Remarks
The FileInfo
class provides properties and methods for creating, moving, and managing files, as well as their properties. This class is thread-safe.
When you create an instance of FileInfo
, it does not create a new file. It simply creates an object that represents an existing file. You can use the Create()
method to create a new file.
Properties
Attributes: Gets or sets the FileAttributes of the current file.
CreationTime: Gets the creation date and time of the file.
CreationTimeUtc: Gets the creation date and time, expressed in Coordinated Universal Time (UTC).
Directory: Gets an instance of DirectoryInfo object representing the directory containing the file.
DirectoryName: Gets the name of the directory that contains the file.
Exists: Gets a value indicating whether the file exists.
Extension: Gets the extension of the file.
FullName: Gets the fully qualified path of the file.
IsReadOnly: Gets or sets a value indicating whether the file is read-only.
LastAccessTime: Gets the date and time the file was last accessed.
LastAccessTimeUtc: Gets the date and time, expressed in Coordinated Universal Time (UTC), that the file was last accessed.
LastWriteTime: Gets the date and time the file was last written to.
LastWriteTimeUtc: Gets the date and time, expressed in Coordinated Universal Time (UTC), that the file was last written to.
Length: Gets the size of the current file in bytes.
Name: Gets the name of the file.
Methods
public FileStream Create()
Creates or overwrites a file in the specified path.
Returns:
FileStream: A new FileStream object.
public void Delete()
Deletes this file.
public void MoveTo(string destFileName)
Moves the current file to a different location.
Parameters:
destFileName: The name of the destination for the current file, which can be a relative or absolute path.
public FileStream Open(FileMode mode)
Opens a file with the specified mode.
Parameters:
mode: A FileMode value that specifies the mode in which to open the file.
public FileStream OpenRead()
Opens an existing file for reading.
Returns:
FileStream: A FileStream object opened for reading.
public FileStream OpenWrite()
Opens an existing file for writing.
Returns:
FileStream: A FileStream object opened for writing.
Example
using System;
using System.IO;
public class Example
{
public static void Main()
{
// Create a FileInfo object for a specific file.
FileInfo fi = new FileInfo(@"C:\MyDir\MyFile.txt");
// Check if the file exists.
if (fi.Exists)
{
Console.WriteLine($"File name: {fi.Name}");
Console.WriteLine($"File size: {fi.Length} bytes");
Console.WriteLine($"Creation time: {fi.CreationTime}");
}
else
{
Console.WriteLine("File does not exist.");
}
}
}