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

如何删除文本文件中除首行外的所有内容?已尝试C#代码未达预期

解决C#删除文本文件除第一行外所有内容的问题

嘿,我来帮你搞定这个问题~你之前的代码只完成了“读取第一行”的第一步,但完全没有把处理后的内容写回文件,而且那个空的foreach循环其实啥也没做,这就是为啥没效果啦。

下面给你几种靠谱的实现方式,按需选择就行:

方法一:简单直观(适合小文件)

用ReadAllLines读取所有行,只保留第一行,再用WriteAllLines覆盖原文件:

// 先用Path.Combine拼接路径,比手动加斜杠更安全
string filePath = Path.Combine(path, "resource.rpf", "__resource.lua");
// 读取所有行并只保留第一行
var firstLine = File.ReadAllLines(filePath).Take(1);
// 将第一行写回文件,覆盖原有内容
File.WriteAllLines(filePath, firstLine);

方法二:内存更高效(适合大文件)

如果你的文件很大,ReadAllLines会把所有内容加载到内存里,这时候用ReadLines(延迟加载)更省内存:

string filePath = Path.Combine(path, "resource.rpf", "__resource.lua");
// ReadLines是延迟读取,只会加载需要的第一行
var firstLine = File.ReadLines(filePath).Take(1);
File.WriteAllLines(filePath, firstLine);

方法三:极致性能(超大文件首选)

如果文件特别大,上面两种方法还是会间接处理所有行,用流的方式直接读取第一行再写入,性能最优:

string filePath = Path.Combine(path, "resource.rpf", "__resource.lua");
// 用StreamReader读取第一行,StreamWriter覆盖写入
using (var reader = new StreamReader(filePath))
using (var writer = new StreamWriter(filePath, false))
{
    string? firstLine = reader.ReadLine();
    if (firstLine != null)
    {
        writer.WriteLine(firstLine);
    }
}

核心要点就是:读取第一行之后,一定要执行写入文件的操作,不然原文件根本不会有变化哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:04:56