0

我正在尝试从文本文件中删除一行文本,使用 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);        
    }

如果有更好的方法来做到这一点,比如使用数组而不是列表,那么实现这种事情的最佳方法是什么。任何帮助表示赞赏,干杯

4

2 回答 2

2
while ((read = reader.ReadLine()) != null)
                {
                    deleteDevice.Clear(); //this is the problem
                    deleteDevice.Add(read);
                }

您在循环的每次迭代期间都在清除您的列表(即,每次您阅读一行时,您都在丢弃行列表)...您需要移到...deleteDevice.Clear()的开头之外while

于 2013-10-24T07:24:10.840 回答
1

您的代码中有许多错误:

1)在阅读时,您不断清除名为 deleteDevice 的 List(Of String)

deleteDevice.Clear();  // <- This line should be removed or moved before entering the loop
deleteDevice.Add(read);

2)在编写时,您将拆分的字符串重新评估为用于循环的同一变量。应该是编译错误,那么您无法删除您在 for each 循环中使用的集合中的项目。您应该使用从最后一个元素开始的普通 for 循环

for(int i = deleteDevice.Count - 1; i>=0; i--)
{
    string split = deleteDevice[i].Split(',');
    List<string> parts = split.ToList(); 
    if (parts.Contains(deviceList.SelectedItem.ToString()))
    {
        deleteDevice.Remove(i);
    }
}
... write to file...
于 2013-10-24T07:34:50.080 回答