Failing to write List


Hi,

I am trying to write data to a text file using the FormClosed event as I just want everything that is in the list sent to a file, no matter how the data has been manipulated while held in memory


string s = myList.Items.ToString();
if(s != null)
{
WriteData(s);
}

static void WriteData(string s)
{
using (TextWriter w = File.AppendText(@"MyData.txt")
{
w.WriteLine(s);
}
}


I have wrapped the first part in a try block, but the exception doesn't seem to catch it.

The text file is full of these lines

System.Windows.Forms.ListBox+ObjectCollection

and it should be full of

my data line 1
my data line 2

etc.,

tia,



Answer this question

Failing to write List

  • Taylor Meek

    Markku is close, try this:
    foreach (object itm in list) {
    writer.WriteLine(itm.ToString());
    }

    Minor detail: use FormClosing so you can keep your form and data alive when the write fails.


  • Marco Minerva

    you can also try this:

    using (StreamWriter theWriter = new StreamWriter("file.txt"))

    {

       foreach(string currentItem in myList.Items)

       {

           theWriter.WriteLine(currentItem); 

       }

    }

    It's pretty much what Markku suggested.

    you need to go through each item in the collections items container and then write that to file.

    At what point are you getting the error



  • winprock

    Hi

    The reason is that your string s store result of ObjectCollection.ToString() method and it return that kind of string.

    Maybe you should change your method something like this:

    private void Form1_FormClosed ( object sender, FormClosedEventArgs e )
    {
    if (myList.Items.Count > 0)
    WriteData(myList.Items);
    }

    public static void WriteData ( System.Collections.ICollection list )
    {
    using(TextWriter writer = File.AppendText(@"MyData.txt"))
    {
    foreach (string str in list)
    writer.WriteLine(str);
    }
    }

    I hope this help you.

    Yours Markku


  • james_cline_

    excellent Markku

    thank you

     

     

    although I'm getting a "cannot convert string from list" error


  • Failing to write List