每次单击按钮时,我可以采取哪些方法从文本文件中删除前 20 或 30 行
本文关键字:文件 文本 删除 方法 按钮 单击 我可以 | 更新日期: 2023-09-27 17:57:03
我正在学习 c# 文本文件处理和字符串操作,我想就单击按钮从文本文件中删除行的最首选方法提出建议。假设,我有一个包含 300 行的文本文件,我想在每次单击按钮时从该文本文件中删除第一个 30 行,并在列表框中显示过滤的项目。
这是我尝试过的,但无法正确处理。.
private void button9_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Text Files|*.txt";
openFileDialog1.Title = "Select a Text file";
openFileDialog1.FileName = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string file = openFileDialog1.FileName;
string[] text = System.IO.File.ReadAllLines(file);
var newLines = File.ReadAllLines(file).Skip(30);
File.WriteAllLines(path, newLines);
foreach (string line in text)
{
listBox1.Items.Add(line);
}
}
}
您需要重写整个文件。一种可读的方法是将 File.ReadAllLines
+ File.WriteAllLines
与Enumerable.Skip
一起使用,这是System.Linq
的一部分:
var newLines = File.ReadAllLines(path).Skip(30);
File.WriteAllLines(path, newLines);