首先引入命名空间
using System.IO;
读TXT文件:
- // 读取TXT文件
- string filePath = @"C:\path\to\file.txt";
-
- if (File.Exists(filePath))
- {
- // 使用 StreamReader 读取文件内容
- using (StreamReader sr = new StreamReader(filePath))
- {
- string content = sr.ReadToEnd();
- Console.WriteLine("文件内容:");
- Console.WriteLine(content);
- }
- }
- else
- {
- Console.WriteLine("文件不存在!");
- }
写TXT文件:
- // 写入TXT文件
- string newFilePath = @"C:\path\to\newfile.txt";
- string newContent = "这是新的文件内容。";
-
- // 使用 StreamWriter 写入文件内容
- using (StreamWriter sw = new StreamWriter(newFilePath))
- {
- sw.Write(newContent);
- Console.WriteLine("文件已写入成功!");
- }
在现有内容后追加写入TXT:
- // 写入TXT文件
- string newFilePath = @"D:\错误日志.txt";
-
- // 使用 StreamWriter 写入文件内容
- using (StreamWriter sw = File.AppendText(newFilePath))
- {
- sw.WriteLine("春哥纯爷们,铁血真汉子。");
-
- }