The list of lines will not be completely written in a text file

I am trying to read from one text file and write to another. The Im reading from file has 2023 lines, and the file that I am writing produces only 2008 lines. I can’t understand what is happening with the other line ... I am losing them somewhere. What am I doing wrong?

thanks!

heres my code in c #.

static void Main(string[] args) { StreamWriter writer = new StreamWriter("C:/Users/Rafael/desktop/newfile.txt"); StreamReader reader = new StreamReader("C:/Users/Rafael/desktop/new1.txt");//, System.Text.Encoding.GetEncoding("ISO-8859-1")); string line; while ((line = reader.ReadLine()) != null) { writer.WriteLine(line); } } 
+4
source share
6 answers

In no case do you close the Streamwriter - therefore, it cannot be written to a file. You can verify this by placing a Close () call after the loop, or if you are not done with the file, you can use Flush ().

Given the choice, I would, however, rewrite the code to use Using{} blocks that automatically close threads, calling Dispose () when they go out of scope.

+9
source

Most likely, the output is not flushed, since you are not calling Dispose() on the record, so the buffered output is rejected.

When you use classes that implement IDisposable this way, you should always wrap them in using blocks:

 static void Main(string[] args) { using (StreamWriter writer = new StreamWriter("C:/Users/Rafael/desktop/newfile.txt")) using (StreamReader reader = new StreamReader("C:/Users/Rafael/desktop/new1.txt")) { string line; while ((line = reader.ReadLine()) != null) { writer.WriteLine(line); } } } 
+5
source

Here, implementation details are important. Basically, when you write StreamWriter text, the text you write is not necessarily bound to a file on disk. Instead, it may be somewhere in the buffer, and this buffer must be cleared to be bound to disk. Periodically, this buffer will be flushed by StreamWriter itself. But if you allow your process to exit without final cleaning, uncommitted entries can still be stored in the buffer.

So, call writer.Flush , writer.Close , writer.Dispose or, best of all, wrap using StreamWriter in the using block so that it is for you.

+3
source

Also, if you do not want to close the file. You can use flush .

+2
source

ReadLine() returns an empty string when the string contains no characters ... Call Flush() and Close() ... consider using using ...

Why don't you just copy the file as a whole ( File.Copy )?

+1
source

Calling Flush() on a Post-Loop Record

0
source

All Articles