Hello,

I have a question, I have a program where I use a stream writer and I write from a list object into a textfile, the only code I put in a while cycle is:

streamwriter1.WriteLine(string);

The application works.

Then I have another program, I have the same situation and I do the same, except that this time in order to enter the strings into the textfile I have to do it this way:

streamwriter1.WriteLine(string);
streamwriter1.Flush();

If I don't put the flush method the string is not entered.

What is the difference, why is that working in one program and in other have to add the flush method?

Thanks

Are you checking the contents of the output file while the program is still running? Normally, when the file is closed (either explicitly, or when the object is disposed and the GC cleans it up), the buffers will be flushed.

If you want to check the status of your output file while the program is still running (e.g., you have a long-running process that's, say, writing a log file), then you will want to call "Flush" on the stream to push the data onto the disk.

A lot of things can affect when the data from a stream is actually written to the file (how long the process runs, how much data you are writing, etc.)

Does one program write more data than the other? A stream has a buffer, that, when it fills up, will be flushed to the disk. If one program is not writing a lot of stuff and you check it while still running, your file may be empty.

Comments
Good point.

Yeah, one program writes a lot of stuff, the other about 10 lines, I guess thats the difference.

Thanks a lot

Use using statement, it provides a convenient syntax that ensures the correct use of IDisposable objects.

using (StreamWriter writer = new StreamWriter("file.txt"))
    {
        //statement here. 
    }
This question has already been answered. Start a new discussion instead.