【发布时间】:2017-08-17 00:08:11
【问题描述】:
我有一个包含文件内容的文本框。我有一个按钮,当它被按下时,它会根据字符串删除一行。代码如下:
private void deleteModuleButton_Click(object sender, EventArgs e)
{
String newText = String.Empty;
List<String> lines = fileContentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
lines.RemoveAll(str => str.Contains(deleteModuleComboBox.Text));
lines.ForEach(str => newText += str + Environment.NewLine);
fileContentTextBox.Text = newText;
}
但是,当删除一行时,它会在文本框底部留下一个空白行。问题在于,当文件被保存时。由于多余的空行,它无法再次读取。当我尝试打开一个在删除一行后保存的文件时出现此错误:“附加信息:索引超出了数组的范围”。当我读取文件时,我将每一行作为字符串,然后使用 "(',')" 分割该行。
有没有办法改变代码,让它接受“newText”,并添加新行,但不是最后一个字符串?或其他方式,以使末尾没有空行。
谢谢
编辑:我搞定了(感谢 L.B)
更新和工作代码:
private void deleteModuleButton_Click(object sender, EventArgs e)
{
String newText = String.Empty;
List<String> lines = fileContentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
lines.RemoveAll(str => str.Contains(deleteModuleComboBox.Text));
newText = string.Join(Environment.NewLine, lines);
fileContentTextBox.Text = newText;
}
【问题讨论】:
-
你试过
fileContentTextBox.Text = string.Join(Environment.NewLine, lines)吗?
标签: c# string file windows-forms-designer