Today, I am going to show you a small demo of how to read, write and delete the text file content in listbox, using C# Window Application.
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 design. Here, I have added one textbox, one list box and three button events to add, delete and view the content from the text file.
Step3
Just add it, using System.IO; namespace in your Server side coding.
Now, begin writing the code for each button event.
Add the new line to the text file.
Just write the code given below in an ADD button event.
- // 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 in Delete button event and while executing, just click the lines which you want to delete from the listbox.
- 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 listBox or you can write this code on page load event, so you can view the content while loading the page.
- 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 would be, as shown below.