C# StreamWriter 完整写入文件教程(新建 / 覆盖 / 追加两种模式)

C# StreamWriter 完整写入文件教程(新建/覆盖 / 追加两种模式)

一、核心构造函数说明

// 参数1:文件路径
// 参数2:append 是否追加
// true = 文件存在就末尾追加;false = 覆盖原有内容(不存在则新建)
new StreamWriter(string path, bool append);

// 完整重载:指定编码、缓冲区大小
new StreamWriter(path, append, Encoding, int bufferSize);

关键:StreamWriter 实现 IDisposable必须用 using 自动释放资源,否则文件会被进程锁定。

二、基础写入方式

方式1:覆盖写入(append=false,默认覆盖)

using System;
using System.IO;

class Demo
{
    static void Main()
    {
        string filePath = "test.txt";
        // append=false:覆盖原有文件
        using (StreamWriter sw = new StreamWriter(filePath, false))
        {
            sw.Write("单行文本"); // 不自动换行
            sw.WriteLine("带换行的内容"); // 自动加\r\n
            sw.WriteLine(12345); // 支持直接写数字
            sw.WriteLine(true); // 布尔值也可直接写入
        }
        // 离开using代码块,自动关闭流、释放文件
    }
}

方式2:追加写入(append=true,在文件末尾新增)

string path = "log.txt";
using (StreamWriter sw = new StreamWriter(path, true))
{
    sw.WriteLine($"日志:{DateTime.Now} 执行操作");
}

三、常用写入方法

方法 作用
Write(string) 写入字符串,不换行
WriteLine(string) 写入字符串 + 自动换行符
Write(数值/布尔) 自动转为字符串写入
Flush() 强制把内存缓冲区数据立刻写入磁盘

Flush 使用场景

循环大量写入时,中途想实时落盘:

using var sw = new StreamWriter("data.txt", true);
for (int i = 0; i < 1000; i++)
{
    sw.WriteLine($"数据行{i}");
    if (i % 100 == 0)
        sw.Flush(); // 每100行刷一次磁盘
}

四、指定编码(避免中文乱码)

默认是 UTF-8(带BOM),可手动指定编码:

// 写入GB2312编码文本
using (StreamWriter sw = new StreamWriter("gbk.txt", false, System.Text.Encoding.GetEncoding("GB2312")))
{
    sw.WriteLine("中文测试");
}

五、循环批量写入(高性能推荐)

循环里只创建一次 StreamWriter,不要每次循环新建:

string path = "batch.txt";
using (StreamWriter sw = new StreamWriter(path, false))
{
    for (int i = 1; i <= 5000; i++)
    {
        sw.WriteLine($"第{i}条记录");
    }
    sw.Flush(); // 循环结束强制刷盘
}

六、异步写入(async/await,UI程序不卡顿)

using System.IO;
using System.Threading.Tasks;

static async Task WriteFileAsync()
{
    string path = "async.txt";
    using (StreamWriter sw = new StreamWriter(path, true))
    {
        await sw.WriteLineAsync("异步写入第一行");
        await sw.WriteLineAsync("异步写入第二行");
        await sw.FlushAsync();
    }
}

七、配合 FileStream 底层写法(高级)

手动控制文件打开模式:

string path = "stream.txt";
// OpenOrCreate:文件不存在新建,存在打开
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
    sw.WriteLine("通过FileStream构造StreamWriter");
}

八、常见坑

  1. 不用 using,文件被占用
    // 错误!无using,文件锁不释放
    StreamWriter sw = new StreamWriter("a.txt", true);
    sw.WriteLine("123");
    // 外部无法删除、修改文件
    
  2. 忘记编码导致中文乱码
    有中文场景建议显式指定 Encoding.UTF8
  3. 循环内反复 new StreamWriter
    会频繁打开关闭磁盘,性能极差,改用单次创建循环写入。

九、最简总结

  1. using(StreamWriter sw = new StreamWriter(路径, 是否追加)) 模板固定;
  2. WriteLine 日常最常用,自动换行;
  3. 批量、循环写入优先使用 StreamWriter,性能远高于 File.AppendAllText;
  4. 离开using自动释放资源,无需手动 Close/Dispose。
posted @ 2026-06-19 20:43  人生就是修炼  阅读(39)  评论(0)    收藏  举报