简体   繁体   中英

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());
            }
        }

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM