Search code examples
c#file-iolistbox

How do you write ListBox items to a text file?


The title basically says it all. I am attempting to convert a ListBox in Visual Studio into a text file. I'm doing this in C#, as it is my most familiar language.

I would imagine that the code that I have would work, but for some reason, it does not. Here is the code that I have so far:

System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(@"C:\WhosTalking\List.txt");
foreach (var item in list.Items)
{
    SaveFile.WriteLine(item.ToString());
}

Any help would be greatly appreciated!


Solution

  • welcome to StackOverflow !

    I just run a very simple example, and apart of making use of using as StreamWriter is a disposable object, all went fine ... I-m just wondering if you have permission to write to the C: drive, and as TheGeneral mentioned, you do need to close the file, hence I've use the using statement, as it does close and dispose the object in one go.

    my simple example:

    enter image description here

    where the file write is:

    private void btnSave_Click(object sender, EventArgs e)
    {
        using (System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(@"D:\List.txt"))
        {
            foreach (var item in listBox.Items)
            {
                SaveFile.WriteLine(item.ToString());
            }
        }
    }