我的任务是从文件中删除一些行。经过一些研究,我得出了这个解决方案:
using (StreamReader reader = new StreamReader (path)
{
using (StreamWriter writer = new StreamWriter(path2))
{
LineIndex=0;
while ((line = reader.ReadLine()) != null)
{
LineIndex++;
if (LineIndex > 6)
break;
}
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine(line);
}
reader.Close();
writer.Close();
if (File.Exists(path2))
{
File.Delete(path);
File.Move(path2, path);
}
}
}
此代码应该读取路径文件,将除前 6 行之外的所有行写入 path2 文件,然后通过覆盖其先前的内容将 path2 文件的内容移动到路径文件。但我得到的是路径文件从所有以前的数据中删除,所以它变成空的。请问有什么解决办法吗?
最佳答案
简单得多:
File.WriteAllLines(path2, File.ReadAllLines(path).Skip(6).ToArray())
这使用 Linq 的 Skip
工作,它返回除前 6 行之外的所有行的数组。另请注意,这适用于较小的文件,因为您将整个文件加载到内存中。
关于c# - 从文件中删除一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34064141/