Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of strings wont get written completely to text file

Tags:

c#

.net

stream

I Im trying to read from one text file and write to another one. The file Im reading from has 2023 lines, and the file that I am writing to comes out with only 2008 lines. I cant figure out what is happening to the other line... Im 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);
        }

    }
like image 569
Rafael Moreira Avatar asked Nov 30 '22 07:11

Rafael Moreira


1 Answers

At no point here are you closing the streamwriter - so it might not be written to the file. You can test this by putting a Close() call after the loop, or if you have not finished with the file, you can use Flush().

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

like image 113
iandotkelly Avatar answered Dec 04 '22 00:12

iandotkelly