我需要从文本文件中删除一行。问题是,当我尝试删除一行时,我必须按两次BtnStergeMedicam才能删除。我不知道为什么要按两次。
private void BtnStergeMedicam_Click(object sender, EventArgs e)
{
string line;
string line_to_delete = ListAfisMedicam.SelectedItem.ToString();//I take the line
//to delete from ListAfisMedicam
using (StreamReader reader = new StreamReader(@"D:\MyTest.txt"))
{
using (StreamWriter writer = new StreamWriter(@"D:\MyTest2.txt"))
{
while ((line = reader.ReadLine()) != null)
{
if (String.Compare(line, line_to_delete) == 0)
continue;
writer.WriteLine(line);
}
writer.Close();
}
reader.Close();
}
System.IO.File.Copy(@"D:\MyTest2.txt", @"D:\MyTest.txt",true);
ListAfisMedicam.Items.Clear();
string[] lines = System.IO.File.ReadAllLines(@"D:\MyTest.txt");
foreach (string linie in lines)
{
ListAfisMedicam.Items.Add(linie);
}
}
答案 0 :(得分:1)
我发现了问题。 ListAfisMedicam.SelectedItem.ToString()
返回给我\nID - 01, Nume - Nurofen, Lot - 0123, Categorie - Capsula, Producator - Dona, Cantitate - 300, DataIntrare - 13-Jan-16 12:00:00 AM, DataFabricarii - 01-Jan-16 12:00:00 AM, DataExpirarii - 31-Jan-16 12:00:00 AM, PretVanzare - 2;
,当它读取每一行并进行比较时,它读起来就像是上层而不是\n
当我第二次尝试时(第二次按下BtnStergeMedicam)ListAfisMedicam.SelectedItem.ToString()
返回ID - 01, Nume -Nurofen ...
编辑:解决问题。谢谢@tom_redox。其他地方的问题。当我填充列表框时,我发了一个\n
,这就是问题所在。坦克你帮助我,从现在开始,每当我遇到任何问题时,我都会开始使用断点