This code writes to a file (it is executed in Windows 10):

class Program { static void Main(string[] args) { StreamWriter sw = new StreamWriter(@"D:\Documents\JS\1.txt"); for (int i = 0; i<=100000;i++) { sw.WriteLine(i.ToString()); } Console.ReadKey(); } } 

However, at the end of the file, I discover:

 99882 99883 99884 99885 99886 99887 99888 99889 99890 9 

If after a cycle I use

 sw.Close(); 

then everything is fine. At work on a PC with Windows 7, he adds to the end.

Why it happens?

    2 answers 2

    StreamWriter and other tools for writing to a file, as a rule, use a buffer in memory to write to the file in blocks.
    Use the .Flush() method to clear the buffer (and write data from it to a file .Flush() . The .Close() method also .Close() buffer, although this is not its main purpose.
    The fact that on some device you have been written to the end is what is called "lucky."

      You did not close StreamWriter .

      Use using :

       using (StreamWriter sw = new StreamWriter(@"D:\Documents\JS\1.txt")) { for (int i = 0; i<=100000;i++) { sw.WriteLine(i.ToString()); } }