# 第九课:文件读写 ## 基本文件操作 ```csharp using System.IO; // 写入文本 File.WriteAllText("test.txt", "你好,无言势字幕"); // 读取文本 string content = File.ReadAllText("test.txt"); ``` ## 路径操作 ```csharp // 路径拼接 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"); ``` ## 读取文件 ```csharp // 方式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); } } ``` ## 写入文件 ```csharp // 方式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): ```csharp 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(jsonStr); Console.WriteLine(p2.Name); // "玩家A" ``` ## 配置文件示例 ```csharp // 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(loaded); ``` ## using 语句自动关闭 ```csharp // StreamReader/Writer 必须关闭,否则文件被锁定 using (StreamReader reader = new StreamReader("test.txt")) { string line = reader.ReadLine(); } // 作用域结束后自动 Close() ``` ## 常见错误处理 ```csharp try { string content = File.ReadAllText("notexist.txt"); } catch (FileNotFoundException) { Console.WriteLine("文件不存在"); } catch (IOException ex) { Console.WriteLine($"IO错误: {ex.Message}"); } ```