Question

so im using this code to save my listview items into a text file:

SaveFileDialog sfd = new SaveFileDialog();
        sfd.InitialDirectory = Application.ExecutablePath;
        sfd.Filter = "Text Files (*.txt)|*.txt";
        sfd.Title = "Save Text file";
        sfd.FileName = "log";
        DialogResult result = sfd.ShowDialog();
        if (result == DialogResult.Cancel)
            return;
        StreamWriter wwrite = new StreamWriter(sfd.FileName, false, Encoding.GetEncoding("SHIFT-JIS"));
        for (int i = 0; i < 14738; ++i)
        {
            wwrite.WriteLine(i.ToString() + "|" + listView1.Items[i].SubItems[1].Text + "|" + listView1.Items[i].SubItems[2].Text + "|" + listView1.Items[i].SubItems[3].Text);
        }

as you can see my listview item count is up to 14738: listview item count but the text file only saved up to 14678 (including the line number 0): line where it stops

i get no error or exception, and i don't think my code is wrong, i've used it many other times, the result was always perfect, i even used it on a listview of more than 32000 items.

Was it helpful?

Solution 2

Make sure that your streamwriter is actually writing everything in the buffer before it closes. You can do this with either

wwrite.Flush()

or by wrapping your streamwriter in a using block. Disposing of a Streamwriter automatically flushes its buffer. Change your code to

using (StreamWriter wwrite = new StreamWriter(sfd.FileName, false, Encoding.GetEncoding("SHIFT-JIS")))
{
    for (int i = 0; i < 14738; ++i)
    {
        wwrite.WriteLine(i.ToString() + "|" + listView1.Items[i].SubItems[1].Text + "|" + listView1.Items[i].SubItems[2].Text + "|" + listView1.Items[i].SubItems[3].Text);
    }
}

OTHER TIPS

Have you tried wrapping the StreamWriter in a using block? I suspect disposing of it will clear any buffers and you'll get all the data.

(edit) or you could call Flush on the StreamWriter. As StreamWriter is IDisposable (link) you really should dispose any instances of it properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top