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.
- // Declare the File Information
- FileInfo file = new FileInfo(@ "C:\Users\shekhart\documents\visual studio 2013\study\Demo\Demo\Demo.txt");
- // write the line using streamwriter
- using(StreamWriter sw = file.AppendText()) {
- sw.WriteLine(textBox1.Text);
- }
- // Read the content using Streamreader from text file
- using(StreamReader sr = file.OpenText()) {
- string s = "";
- while ((s = sr.ReadLine()) != null) {
- listBox1.Text = s; // Display the text file content to the list box
- }
- sr.Close();
- }
Delete the line from the text file
Write the code given below at the Delete button click event hander.
- string path = @ "C:\Users\shekhart\documents\visual studio 2013\study\Demo\Demo\Demo.txt";
- string word = Convert.ToString(listBox1.SelectedItem);
- var oldLines = System.IO.File.ReadAllLines(path);
- var newLines = oldLines.Where(line => !line.Contains(word));
- System.IO.File.WriteAllLines(path, newLines);
- FileStream obj = new FileStream(path, FileMode.Append);
- obj.Close();
-
- FileInfo fi = new FileInfo(@ "C:\Users\shekhart\documents\visual studio 2013\study\Demo\Demo\Demo.txt");
- using(StreamReader sr = fi.OpenText()) {
- string s = "";
- while ((s = sr.ReadLine()) != null) {
- listBox1.Text = s;
- }
- sr.Close();
- }
- FileStream obj1 = new FileStream(path, FileMode.Append);
- 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.
- string[] lines = System.IO.File.ReadAllLines(@ "C:\Users\shekhart\documents\visual studio 2013\study\Demo\Demo\Demo.txt");
- foreach(string line in lines)
- {
- listBox1.Items.Add(line);
- }
The output looks like the following.