7

I've got a list of 369 different names and I want to print these names into a csv file. All's going well until I take a look at the outputted csv file and it only has 251 rows. I've tried outputting to a .txt instead, and still it only outputs 251 rows. Ive stepped through with the debugger and it is still calling writer.WriteLine() 369 times.

Is there some sort of writing restriction in place? If so, why 251? How do I write all 369 names?

Here's my code just in case:

List<String> names = new List<String>();

//Retrieve names from a separate source.

var writer = new StreamWriter(File.OpenWrite(@"C:names.txt"));
        for (int i = 0; i < names.Count; i++ )
        {
            System.Console.WriteLine(names[i].ToString());
            writer.WriteLine(names[i].ToString());
        }
        System.Console.Write(names.Count);

The output on the console shows all 369 names and the names.Count prints 369.

Jimmy T
  • 447
  • 6
  • 14

4 Answers4

11

You need to close your StreamWriter, the best way is to use a using block like so:

using(StreamWriter writer = new StreamWriter(File.OpenWrite("C:\\names.txt")) {
    // code here
}

The using block will always call the .Dispose method of StreamWriter which has the effect of flushing the stream. Presently you have buffered-but-unwritten data in your StreamWriter instance.

Silvermind
  • 5,791
  • 2
  • 24
  • 44
Dai
  • 141,631
  • 28
  • 261
  • 374
  • Thanks! Simply calling writer.close worked but I'll make sure to start using 'using' from now on. Can't believe it was such a simple error... – Jimmy T Dec 17 '13 at 02:25
4

You do not show anywhere that you properly close writer. If your program terminates abnormally, the writer would never be flushed to disk.

Try making use of a using block.

// NOTE: The is should be C:\names.txt.  The posted code is missing a \
using (var writer = new StreamWriter(File.OpenWrite(@"C:names.txt")))
{
    // Your code here
}
Eric J.
  • 147,927
  • 63
  • 340
  • 553
1

You have to flush buffer after last write. Put writer inside using statement. Dispose method of writer flushes buffer. You can also call writer.Flush(). But since you still have to make sure that writer is disposed just put it in a using statement as other suggested.

  • Just calling `Dispose()` is not the same as `using`, unless `Dispose()` is in a `finally` block. – Eric J. Dec 17 '13 at 02:33
0
List<String> names = new List<String>();
var sb = new StringBuilder()
//Retrieve names from a separate source.


        for (int i = 0; i < names.Count; i++ )
        {
            System.Console.WriteLine(names[i].ToString());
            sb.WriteLine(names[i].ToString());
        }
using (var writer = new StreamWriter(File.OpenWrite(@"C:\names.txt")))
{
    writer.WriteLine(sb.ToString());
}
AD.Net
  • 13,352
  • 2
  • 28
  • 47