C# Save all items in a ListBox to text file

Viewed 51614

Recently I've been quite enjoying C# and I'm just testing with it but there seems to be one part I don't get.

Basically I want it so that when I click the SAVE button must save all the items in the listbox to a text file. At the moment all it comes up with in the file is System.Windows.Forms.ListBox+ObjectCollection.

Here's what I've got so far. With the SaveFile.WriteLine(listBox1.Items); part I've tried putting many different methods in and I can't seem to figure it out. Also take in mind that in the end product of my program I would like it to read back to that to that text file and output what's in the text file to the listbox, if this isn't possible then my bad, I am new to C# after all ;)

private void btn_Save_Click(object sender, EventArgs e)
{
    const string sPath = "save.txt";

    System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
    SaveFile.WriteLine(listBox1.Items);
    SaveFile.ToString();
    SaveFile.Close();

    MessageBox.Show("Programs saved!");
}
3 Answers

There is one line solution to the problem.

System.IO.File.WriteAllLines(path, Listbox.Items.Cast<string>().ToArray());

put your file path+name and Listbox name in above code.

Example: in Example below path and name of the file is D:\sku3.txt and list box name is lb System.IO.File.WriteAllLines(@"D:\sku3.txt", lb.Items.Cast<string>().ToArray());

Related