-2

First i Read all lines of a text file line by line and store it in a string-array. Then i write it with file.WriteLine() into a file. The opened Console window shows every line which was written into the file, but when i open the file to check if it did well, the last 10-20 lines are missing.

Any ideas?

 string[] lines = System.IO.File.ReadAllLines(@"C:\Users\XXX\Desktop\Dok1.csv");
            StreamWriter file = new StreamWriter(@"C:\Users\XXX\Desktop\test2.csv");
            
            foreach(string line in lines)
            {
                file.WriteLine(line);
                Console.WriteLine(line);
            }

Console output: Redunderlined is the last line

Comparison Written File vs. Read File(Written file is missing last lines)

Liam
  • 27,717
  • 28
  • 128
  • 190
Phil
  • 19
  • 4
  • 8
    You don't dispose your `StreamWriter` -- it will be buffering some text internally, which never gets flushed. Using a `using` block – canton7 Jan 12 '21 at 13:09
  • Are your lines fixed length? perhaps https://github.com/dotnet/corefxlab/tree/master/src/Microsoft.Data.Analysis – Jay Jan 12 '21 at 13:10
  • @canton7 ahhh, well, that was quick. It worked with the using-block. Thank you :) – Phil Jan 12 '21 at 13:16

1 Answers1

1
    using(StreamWriter file = new StreamWriter(@"C:\Users\XXX\Desktop\test2.csv"))
    {
        foreach(string line in lines)
        {
            file.WriteLine(line);
            Console.WriteLine(line);
        }
    }

The Using statement closes the stream forcing the write of the internal buffer.

Cleptus
  • 3,446
  • 4
  • 28
  • 34