Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my C# program only write 251 rows to a file?

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.

like image 699
Jimmy T Avatar asked Dec 17 '13 02:12

Jimmy T


People also ask

Why my C drive is always full?

Mostly, useless large junk files, big files, huge installed programs, and temporary files are taking up the most space in your system C drive after using your PC for a long time. So the other effective method you can try is to free up hard disk space.

Why is my C drive losing space?

As the article explained, there are mainly three reasons why your hard drive capacity shows less than the actual size, including a huge hidden recovery partition, computer virus, and invisible unallocated space out of the whole disk partition.

Why is my C drive full with nothing on it?

When the hard drive's file system gets corrupted, it will show the capacity incorrectly and cause the C drive is full for no reason problem. You can use a hard drive repair tool - EaseUS Partition Master to check and repair back sectors by fixing the file system errors with the Check File System feature.


1 Answers

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.

like image 91
Dai Avatar answered Oct 27 '22 00:10

Dai