CSharp-Learning/notes/09_File_IO.md
Rosmontis_Cloud f604d53191 Initial commit: C# 学习笔记和示例代码
- Lesson 01-10: C# 基础语法
- WebView2: 集成示例
- notes/: 详细笔记
2026-07-01 16:31:35 +08:00

3.2 KiB
Raw Blame History

第九课:文件读写

基本文件操作

using System.IO;

// 写入文本
File.WriteAllText("test.txt", "你好,无言势字幕");

// 读取文本
string content = File.ReadAllText("test.txt");

路径操作

// 路径拼接
string path = Path.Combine("C:", "Users", "test", "config.json");

// 获取扩展名
string ext = Path.GetExtension("test.txt");  // ".txt"

// 获取文件名
string name = Path.GetFileName("C:/test/test.txt");  // "test.txt"

// 判断文件是否存在
bool exists = File.Exists("config.json");

读取文件

// 方式1一次性读取适合小文件
string content = File.ReadAllText("test.txt");

// 方式2按行读取
string[] lines = File.ReadAllLines("test.txt");
foreach (string line in lines)
{
    Console.WriteLine(line);
}

// 方式3流式读取大文件
using (StreamReader reader = new StreamReader("test.txt"))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        Console.WriteLine(line);
    }
}

写入文件

// 方式1一次性写入
File.WriteAllText("output.txt", "内容");

// 方式2按行写入
string[] lines = { "第一行", "第二行", "第三行" };
File.WriteAllLines("output.txt", lines);

// 方式3追加内容
File.AppendAllText("log.txt", "新追加的内容\n");

// 方式4流式写入
using (StreamWriter writer = new StreamWriter("output.txt"))
{
    writer.WriteLine("第一行");
    writer.WriteLine("第二行");
}

JSON 序列化

.NET 内置 JSON 支持System.Text.Json

using System.Text.Json;
using System.Text.Json.Serialization;

// 序列化(对象 -> JSON
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Person p = new Person { Name = "无言势", Age = 25 };
string json = JsonSerializer.Serialize(p);
Console.WriteLine(json);
// 输出: {"Name":"无言势","Age":25}

// 反序列化JSON -> 对象)
string jsonStr = "{\"Name\":\"玩家A\",\"Age\":30}";
Person p2 = JsonSerializer.Deserialize<Person>(jsonStr);
Console.WriteLine(p2.Name);  // "玩家A"

配置文件示例

// AppSettings 类
class AppSettings
{
    public int Sensitivity { get; set; } = 70;
    public bool AutoConnect { get; set; } = true;
    public bool VadEnabled { get; set; } = true;
    public string Language { get; set; } = "zh-CN";
}

// 保存配置
AppSettings settings = new AppSettings();
string json = JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText("config.json", json);

// 读取配置
string loaded = File.ReadAllText("config.json");
AppSettings loadedSettings = JsonSerializer.Deserialize<AppSettings>(loaded);

using 语句自动关闭

// StreamReader/Writer 必须关闭,否则文件被锁定
using (StreamReader reader = new StreamReader("test.txt"))
{
    string line = reader.ReadLine();
}
// 作用域结束后自动 Close()

常见错误处理

try
{
    string content = File.ReadAllText("notexist.txt");
}
catch (FileNotFoundException)
{
    Console.WriteLine("文件不存在");
}
catch (IOException ex)
{
    Console.WriteLine($"IO错误: {ex.Message}");
}