You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何向文本文件追加写入多条内容 现有代码每次覆盖原有数据如何解决

问题根因

你当前代码中调用的File.Create(path)方法特性为:若目标路径已存在同名文件,会直接删除原有文件并创建全新的空文件,因此每次写入的内容都会覆盖之前的内容,无法实现多条内容追加。

修复方案

推荐使用File.AppendText的简洁写法,自动实现文件末尾追加,不存在的文件会自动创建,同时搭配using语句自动释放文件资源,无需手动调用Close(),避免异常场景下的资源泄漏:

string path = @"data.txt";
private void buttonInsert_Click(object sender, EventArgs e)
{
    using (StreamWriter sw = File.AppendText(path))
    {
        // 若需要每条新增内容单独占一行,可替换为 sw.WriteLine(textBox1.Text)
        sw.Write(textBox1.Text);
    }
    textBox1.Clear();
}

如果你希望保留FileStream的写法,修改时指定FileMode.Append枚举即可实现追加效果:

string path = @"data.txt";
private void buttonInsert_Click(object sender, EventArgs e)
{
    using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
    using (StreamWriter sw = new StreamWriter(fs))          
    {
        sw.Write(textBox1.Text);
    }
    textBox1.Clear();
}

内容的提问来源于stack exchange,提问作者PerkZz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:06:02