我正在尝试从文本文件中删除一行文本,使用 StreamReader 导入文件,将内容添加到列表中,删除所需的行,重新写入没有该行的文本文件。但是,任何运行程序的尝试似乎都会导致无限循环,从文件中清除所有字符串,或者根本没有清除一个文件。这是我的代码:
{
string read = "";
if (devOutput.Count() != 0) //Error Handling
{
using (StreamReader reader = new StreamReader("Devices.txt", true))
{
while ((read = reader.ReadLine()) != null)
{
deleteDevice.Clear();
deleteDevice.Add(read);
}
}
}
else
MessageBox.Show("2: No Devices Saved!");
using (StreamWriter writer = new StreamWriter("Devices.txt"))
{
do
{
foreach (string st in deleteDevice)
{
string split = st.ToString();
deleteDevice = split.Split(',').ToList();
}
if (deleteDevice.Contains(deviceList.SelectedItem.ToString()))
{
deleteDevice.Remove(i.ToString());
i = i + 1;
deleteDevice.Remove(i.ToString());
i = i + 1;
deleteDevice.Remove(i.ToString());
i = i + 1;
deleteDevice.Remove(i.ToString());
i = i + 1;
deleteDevice.Remove(i.ToString());
i = i + 4; //Progress to next device
}
}
while (i < deleteDevice.Count);
if (deleteDevice.Count != 0) //Error Handling
{
foreach (string st in deleteDevice)
{
writer.WriteLine(st);
}
}
}
deviceList.Items.Remove(deviceList.SelectedItem);
}
如果有更好的方法来做到这一点,比如使用数组而不是列表,那么实现这种事情的最佳方法是什么。任何帮助表示赞赏,干杯