How to Delete Text File Content in C#

Today, I am going to show you a small demo of how to read, write and delete the text file content in a Windows Forms ListBox control.
 
Step1

Create one empty text file and named it as your desired name and add into your project, as shown below.

 
Step 2

Create a form. In my case, I have added a TextBox, a ListBox, and three Button controls. Double click on buttons to add event handlers for these buttons.
 
 
 
Step3

Add using System.IO; namespace in your C# file. 
 
Now, begin writing code for each button click event handler. 
 
Add the new line to the text file.
 
ADD button click event handler.
  1. // Declare the File Information   
  2. FileInfo file = new FileInfo(@ "C:\Users\shekhart\documents\visual studio 2013\study\Demo\Demo\Demo.txt");  
  3. // write the line using streamwriter   
  4. using(StreamWriter sw = file.AppendText()) {  
  5.     sw.WriteLine(textBox1.Text);  
  6. }  
  7. // Read the content using Streamreader from text file   
  8. using(StreamReader sr = file.OpenText()) {  
  9.     string s = "";  
  10.     while ((s = sr.ReadLine()) != null) {  
  11.         listBox1.Text = s; // Display the text file content to the list box  
  12.     }  
  13.     sr.Close();  
  14. }   
Delete the line from the text file
 
Write the code given below at the Delete button click event hander. 
  1. string path = @ "C:\Users\shekhart\documents\visual studio 2013\study\Demo\Demo\Demo.txt";  
  2. string word = Convert.ToString(listBox1.SelectedItem); // delete the selected line  
  3. var oldLines = System.IO.File.ReadAllLines(path);  
  4. var newLines = oldLines.Where(line => !line.Contains(word));  
  5. System.IO.File.WriteAllLines(path, newLines);  
  6. FileStream obj = new FileStream(path, FileMode.Append);  
  7. obj.Close();  
  8. // once deleted the selected line and once again read the text file and diplay the new text file in listBox  
  9. FileInfo fi = new FileInfo(@ "C:\Users\shekhart\documents\visual studio 2013\study\Demo\Demo\Demo.txt");  
  10. using(StreamReader sr = fi.OpenText()) {  
  11.     string s = "";  
  12.     while ((s = sr.ReadLine()) != null) {  
  13.         listBox1.Text = s;  
  14.     }  
  15.     sr.Close();  
  16. }  
  17. FileStream obj1 = new FileStream(path, FileMode.Append);  
  18. obj1.Close();   
View the entered content from the text file

Now, write code to view the content of the text file in a ListBox. You can also write this code on Window load event handler.
  1. string[] lines = System.IO.File.ReadAllLines(@ "C:\Users\shekhart\documents\visual studio 2013\study\Demo\Demo\Demo.txt");  
  2. foreach(string line in lines) // Read all line from the text file  
  3. {  
  4.     listBox1.Items.Add(line);  
  5. }   
The output looks like the following.

 
 
Learn more here: Files in C# and .NET.