从List <string>中删除项目,源自文本文件</string>

时间:2013-10-24 07:21:54

标签: c# arrays string streamreader streamwriter

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

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

2 个答案:

答案 0 :(得分:2)

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

您正在循环的每次迭代期间清除列表(即每次读取行时都会破坏行列表)...您需要将deleteDevice.Clear()移到{{1}的开头之外}} ...

答案 1 :(得分: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...