1

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.

Omarrrio
  • 1,075
  • 1
  • 16
  • 34

2 Answers2

2

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.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
1

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);
    }
}
cost
  • 4,420
  • 8
  • 48
  • 80
  • Thank you, that was the answer, i wraped it with a using block, made it save faster. – Omarrrio Dec 30 '13 at 01:40
  • 1
    @Omarrrio a using block is very useful for instances like this where you're using your streamwriter for a single, simple thing. If you're ever using a streamwriter for multiple operations, flush is probably a better bet. – cost Dec 30 '13 at 01:42