Reputation: 51
I'm trying to remove a line of text from a text file, using StreamReader to import the file, adding the contents to a list, removing the desired line, the re-writing to the text file without the line. However, any attempts at running the program seem to result in either infinite loops, all strings cleared from the file, or one file not being cleared at all. Here's the code I have:
{
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);
}
If there is a better way of doing this, say using an array instead of a List, what would be the best way to implement such a thing. Any help is appreciated, Cheers
Upvotes: 0
Views: 723
Reputation: 216352
There are a number of errors in your code:
1) While reading you constantly clear the List(Of String) called deleteDevice
deleteDevice.Clear(); // <- This line should be removed or moved before entering the loop
deleteDevice.Add(read);
2) While writing you reassing the splitted string to the same variable used to loop over. Should be a compilation error, then you can't remove an item on the collection that you use in the for each loop. You should use a normal for loop starting from the last element
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...
Upvotes: 1
Reputation: 7505
while ((read = reader.ReadLine()) != null)
{
deleteDevice.Clear(); //this is the problem
deleteDevice.Add(read);
}
You are clearing your list during each iteration of the loop (i.e every time you read a line you are trashing the list of lines)...you need to move deleteDevice.Clear()
outside the start of the while
...
Upvotes: 2