C# 文件类
最后修改于 2025 年 4 月 20 日
本教程解释了如何在 C# 中使用 File 类执行各种文件操作。 File 类提供了用于创建、复制、删除、移动和打开文件的静态方法。
File 类是 System.IO 命名空间的一部分,并为文件操作提供静态方法。 它通过提供即用型功能简化了文件操作。
File 方法通常用于单个文件操作。 对于更复杂的场景,请考虑使用 FileStream 或 StreamReader/StreamWriter 类。
检查文件是否存在
此示例演示了如何在对文件执行操作之前检查文件是否存在。 Exists 方法用于此目的。
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "test.txt";
if (File.Exists(filePath))
{
Console.WriteLine("File exists");
Console.WriteLine($"Last write time: {File.GetLastWriteTime(filePath)}");
}
else
{
Console.WriteLine("File does not exist");
File.Create(filePath).Close();
Console.WriteLine("Created new file");
}
}
}
该程序检查文件是否存在,如果存在,则显示其上次写入时间。 如果文件不存在,则创建一个新的空文件。 Exists 方法返回一个布尔值,指示该文件是否存在于指定的路径中。
GetLastWriteTime 检索文件上次修改的日期时间。 File.Create 创建一个新文件并返回一个 FileStream,由于我们不需要它,因此我们立即关闭它。 始终在操作前检查文件是否存在,以避免异常。
读取和写入文本文件
File 类提供了用于读取和写入文本文件的简单方法。 此示例显示了基本的文件 I/O 操作。
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "data.txt";
// Write to file
File.WriteAllText(filePath, "Hello File Class!\nThis is a second line.");
// Append to file
File.AppendAllText(filePath, "\nThis line was appended.");
// Read from file
string content = File.ReadAllText(filePath);
Console.WriteLine("File content:");
Console.WriteLine(content);
// Read lines separately
string[] lines = File.ReadAllLines(filePath);
Console.WriteLine("\nLine count: " + lines.Length);
}
}
WriteAllText 使用指定的内容创建或覆盖文件。 AppendAllText 将内容添加到现有文件中。 ReadAllText 将整个文件内容读取为单个字符串。
ReadAllLines 将文件内容读取为字符串数组,每个元素代表一行。 这些方法自动处理文件打开、写入/读取和关闭。 它们对于小型文件很方便,但由于内存使用情况,可能不适用于非常大的文件。
复制和移动文件
此示例演示了使用 File 类方法进行文件复制和移动操作。
using System;
using System.IO;
class Program
{
static void Main()
{
string sourceFile = "source.txt";
string destFile = "destination.txt";
string movedFile = "moved.txt";
// Create source file
File.WriteAllText(sourceFile, "This is the source file content.");
// Copy file
File.Copy(sourceFile, destFile);
Console.WriteLine($"File copied to {destFile}");
// Move file
File.Move(destFile, movedFile);
Console.WriteLine($"File moved to {movedFile}");
// Verify operations
Console.WriteLine($"Source exists: {File.Exists(sourceFile)}");
Console.WriteLine($"Destination exists: {File.Exists(destFile)}");
Console.WriteLine($"Moved file exists: {File.Exists(movedFile)}");
}
}
File.Copy 在指定的目标路径创建源文件的副本。 默认情况下,它不会覆盖现有文件,除非将 overwrite 参数设置为 true。 File.Move 将文件传输到新位置,也可用于重命名文件。
当在同一卷内执行时,移动操作是原子的。 对于跨卷移动,它实际上是一个复制操作,后跟删除操作。 始终在这些操作之前检查文件是否存在,以避免异常。 这些方法尽可能保留文件属性和时间戳。
文件信息和属性
File 类提供了检索各种文件属性和属性的方法。 此示例显示了如何访问此信息。
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "info.txt";
File.WriteAllText(filePath, "Sample content for file information demo.");
// Get file information
DateTime creationTime = File.GetCreationTime(filePath);
DateTime lastWriteTime = File.GetLastWriteTime(filePath);
DateTime lastAccessTime = File.GetLastAccessTime(filePath);
FileAttributes attributes = File.GetAttributes(filePath);
Console.WriteLine($"File: {filePath}");
Console.WriteLine($"Created: {creationTime}");
Console.WriteLine($"Last modified: {lastWriteTime}");
Console.WriteLine($"Last accessed: {lastAccessTime}");
Console.WriteLine($"Attributes: {attributes}");
// Check specific attributes
bool isReadOnly = (attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
bool isHidden = (attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
Console.WriteLine($"ReadOnly: {isReadOnly}");
Console.WriteLine($"Hidden: {isHidden}");
}
}
该示例检索文件的各种时间戳和属性。 GetCreationTime、GetLastWriteTime 和 GetLastAccessTime 返回表示重要文件事件的 DateTime 对象。 GetAttributes 返回文件属性的位掩码。
文件属性使用按位运算进行检查。 该示例检查 ReadOnly 和 Hidden 标志。 其他常见属性包括 Archive、System 和 Directory。 这些方法对于需要检查文件属性的文件管理应用程序和实用程序非常有用。
删除文件
此示例演示了使用 File 类删除文件。 它展示了安全删除实践和错误处理。
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "temporary.txt";
File.WriteAllText(filePath, "This file will be deleted.");
Console.WriteLine($"File exists before deletion: {File.Exists(filePath)}");
try
{
File.Delete(filePath);
Console.WriteLine("File deleted successfully.");
// Attempt to delete non-existent file
File.Delete("nonexistent.txt");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Console.WriteLine($"File exists after deletion: {File.Exists(filePath)}");
}
}
File.Delete 永久删除指定的文件。 与移动到回收站不同,此操作是不可逆的。 如果文件不存在,该方法不会引发异常,因此可以安全地调用它而无需存在性检查。
但是,由于其他原因,例如权限不足或文件正在使用中,可能会发生异常。 在执行文件操作时,始终处理潜在的异常。 对于关键应用程序,请考虑在删除前实施备份或确认机制。
使用文件流
虽然 File 类提供了高级方法,但它也可以创建文件流以进行更多控制。 此示例显示了基于流的文件操作。
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string filePath = "streamdata.bin";
// Write using FileStream
using (FileStream fs = File.Create(filePath))
{
byte[] data = Encoding.UTF8.GetBytes("Stream-based file content");
fs.Write(data, 0, data.Length);
fs.Flush();
}
// Read using FileStream
using (FileStream fs = File.OpenRead(filePath))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string content = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Read content: " + content);
}
// Alternative open methods
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite))
{
// Can perform both read and write operations
fs.Position = 0;
byte[] newData = Encoding.UTF8.GetBytes("Updated ");
fs.Write(newData, 0, newData.Length);
}
}
}
File.Create 和 File.OpenRead 返回用于字节级文件操作的 FileStream 对象。 File.Open 通过 FileMode 和 FileAccess 参数提供更多控制。 流非常适合大型文件,或者当您需要精确控制读取/写入时。
该示例显示了将字节写入文件并将它们读回。 Flush 确保所有缓冲数据都写入磁盘。 流实现 IDisposable,因此应在 using 语句中使用它们以进行正确的资源清理。 这种方法比高级方法更灵活,但需要更多代码。
文件加密和解密
File 类提供了使用当前用户的凭据进行简单文件加密的方法。 此示例演示了基本的文件加密和解密。
using System;
using System.IO;
using System.Security.AccessControl;
class Program
{
static void Main()
{
string originalFile = "original.txt";
string encryptedFile = "encrypted.txt";
string decryptedFile = "decrypted.txt";
File.WriteAllText(originalFile, "This is sensitive data that needs protection.");
try
{
// Encrypt the file
File.Encrypt(originalFile);
Console.WriteLine("File encrypted successfully.");
// Copy the encrypted file
File.Copy(originalFile, encryptedFile);
// Decrypt the original file
File.Decrypt(originalFile);
Console.WriteLine("File decrypted successfully.");
// Verify by reading decrypted content
string content = File.ReadAllText(originalFile);
Console.WriteLine("Decrypted content: " + content);
}
catch (PlatformNotSupportedException)
{
Console.WriteLine("Encryption not supported on this platform.");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
File.Encrypt 和 File.Decrypt 在可用时使用 Windows EFS(加密文件系统)。 加密与当前用户帐户相关联 - 其他用户无法解密该文件。 这些方法仅在 Windows 平台上可用。
该示例加密一个文件,在加密时复制它,然后解密原始文件。 请注意,加密支持取决于文件系统和操作系统。 始终处理潜在的异常,并为不支持的方案提供回退机制。 对于跨平台应用程序,请考虑其他加密库。
来源
本教程介绍了使用 File 类在 C# 中进行的各种文件操作,包括读取、写入、复制、移动和加密文件。
作者
列出所有 C# 教程。