How to delete row from text file?

delete a row from a list

  • i have a form with 6 textboxes and a delete button.that i want to do is to read a text file and save it into a list.after that i want to give a value at the textbox1 and delete the row from the list that this value exists.with this code(i have already done) delete all the values from the text file.what should i change to the code?i use Microsoft Visual C# 2010 Express. List<string> StoreItems; public Form1() { InitializeComponent(); filePath = @"C:\Users\v\Desktop\text.txt"; StoreItems = new List<string>(); } private void button3_Click(object sender, EventArgs e) { using (var streamReader = new StreamReader(filePath, Encoding.Default)) { while (!streamReader.EndOfStream) { StoreItems.Add(streamReader.ReadLine()); } } using (var streamWriter = new StreamWriter(filePath, false, Encoding.Default)) { foreach (string line in StoreItems) { if(line == textBox1.Text)//remove all from the list StoreItems.Remove(line); } } }

  • Answer:

    You can use http://msdn.microsoft.com/en-us/library/wdka673a.aspx. Removes all the elements that match the conditions defined by the specified predicate. There's no need for explicit iteration over the list. You can just call it like this: StoreItems.RemoveAll(item => item == textBox1.Text); You also forgot to write the list back to the file. I think you want code like this: using (var streamReader = new StreamReader(filePath, Encoding.Default)) { while (!streamReader.EndOfStream) { StoreItems.Add(streamReader.ReadLine()); } } StoreItems.RemoveAll(item => item == textBox1.Text); using (var streamWriter = new StreamWriter(filePath, false, Encoding.Default)) { foreach (string line in StoreItems) { streamWrite.WriteLine(line); } }

leki arnold at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

using (var streamReader = new StreamReader(filePath, Encoding.Default)) { while (!streamReader.EndOfStream) { StoreItems.Add(streamReader.ReadLine()); } } int i = StoreItems.IndexOf(textBox1.Text); while (i >= 0) { StoreItems.RemoveAt(i); i = StoreItems.IndexOf(textBox1.Text); }

alexm

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.