Reputation: 487
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.
Upvotes: 7
Views: 206
Reputation: 155290
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.
Upvotes: 11
Reputation: 885
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.
Upvotes: 1
Reputation: 13399
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());
}
Upvotes: 0
Reputation: 150118
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
}
Upvotes: 4