C# 文件操作实战指南:Exists、ReadAllLines、ReadAllText、Copy、Delete
C# 文件操作实战指南
在 C# 和 .NET 中处理文件是常见需求。无论验证文件存在、读取内容、管理文件复制,System.IO.File 类提供直观、线程安全的方法。下面给出简明解释和遵循最佳实践及微软官方指导的示例代码。
基本文件操作
- 读取 – 从现有文件检索数据。
- 写入 – 用新内容覆盖整个文件(默认行为)。
- 追加 – 在不删除现有内容情况下向文件末尾添加数据。
覆盖的关键方法
File.Exists– 检查文件是否存在。File.ReadAllLines– 将所有行加载到字符串数组。File.ReadAllText– 将整个文件加载为单个字符串。File.Copy– 复制文件到新位置。File.Delete– 从文件系统删除文件。
前置条件
所有示例假设文本文件 D:\Example.txt 存在,内容两行:
Guru99 – .Net Guru99 – C#
1. 检查文件存在 – File.Exists
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string path = "D:\\Example.txt";
if (File.Exists(path)) {
Console.WriteLine("File Exists");
} else {
Console.WriteLine("File Not Found");
}
Console.ReadKey();
}
}
}
当 D:\Example.txt 存在时程序输出 File Exists。
2. 逐行读取 – File.ReadAllLines
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string path = "D:\\Example.txt";
string[] lines = File.ReadAllLines(path);
foreach (var line in lines) {
Console.WriteLine(line);
}
Console.ReadKey();
}
}
}
文件每行在控制台单独打印。
3. 读取整个文件 – File.ReadAllText
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string path = "D:\\Example.txt";
string content = File.ReadAllText(path);
Console.WriteLine(content);
Console.ReadKey();
}
}
}
控制台显示两行并以换行符连接。
4. 复制文件 – File.Copy
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string source = "D:\\Example.txt";
string destination = "D:\\ExampleNew.txt";
File.Copy(source, destination, overwrite: true);
Console.WriteLine("Copy succeeded");
Console.ReadKey();
}
}
}
新文件 D:\ExampleNew.txt 包含 Example.txt 的确切副本。
5. 删除文件 – File.Delete
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string path = "D:\\Example.txt";
File.Delete(path);
Console.WriteLine("File deleted");
Console.ReadKey();
}
}
}
执行后 D:\Example.txt 从 D 盘永久移除。
总结
System.IO.File类提供基本文件系统操作。- 用
File.ReadAllText或File.ReadAllLines将文件数据读入应用。 - 生产代码中始终处理
FileNotFoundException或UnauthorizedAccessException等异常。
C语言
- 单点I/O保护:熔断器还是断路器?
- Axiomtek IPS960-511-PoE:面向工业检测的一体化坚固视觉控制器
- 掌握 C# using 指令:命名空间导入、别名与静态导入全解析
- C 语言输入输出(I/O)精通:scanf() 与 printf() 详解
- C语言文件处理完全指南:fopen、fprintf、fread 与 fseek
- C 语言文件 I/O 实战:创建、打开、读写与二进制操作
- C 语言头文件详解:类型、用法与最佳实践
- C 语言错误处理最佳实践:errno、perror 与 strerror 详解
- C# 异常处理完全指南:try-catch-finally、异常类型、自定义异常与最佳实践
- C# 文件 I/O 完全指南:流、读写操作与文件系统管理
- Python 文件 I/O:掌握文件操作、读写与管理
- Python 文件 I/O:掌握输入输出操作