Amar
Amar

Reputation: 529

Save ListBox items to file

I'm trying to create a file, add all the listbox items to the file. SO I can later on open the file and show all the listbox items again.

My current code is not working, it wont create a file or save to a existing file.

Function to get the name of thefile created / path

private void mnuFileSaveAs_Click(object sender, EventArgs e)
    {
        string fileName = "";
        SaveFileDialog sfd = new SaveFileDialog();
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            if(fileName == String.Empty)
            {
                mnuFileSaveAs_Click(sender, e);
            }
            else
            {
                fileName = sfd.FileName;
                writeToFile(fileName);
            }

        }

    }

Function to write to file

private void writeToFile(string fileName)
        {
            System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fileName);
            foreach (var item in listBox.Items)
            {
                SaveFile.WriteLine(item.ToString());
            }
        }

enter image description here

Upvotes: 0

Views: 1725

Answers (1)

romerotg
romerotg

Reputation: 464

Well you didn't specify the error, but my guess is that it isn't working because you didn't close the StreamWriter.

using (System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fileName))
{
    foreach (var item in listBox.Items)
        SaveFile.WriteLine(item.ToString());
}

Or you can just call SaveFile.Close() instead of using

Upvotes: 3

Related Questions