0

I have a code like the following one for working with a TextWriter stream.

TextWriter TR = new StreamWriter(@"")

try
{

    //Logic

}
catch (Exception exception)
{

    //Error Reporting

}
finally
{

    if (TR != null)
        TR.Close();

}

My .Net version is 4.0 and this code works properly on Windows 7 but it does not work properly in Windows XP!! It seems that the stream does not close and a number of buffers are not written to file! I have no idea! Can anyone help me to solve this problem please?

moorara
  • 3,897
  • 10
  • 47
  • 60
  • 1
    Maybe not a direct solution but please also look at the `using` keyword for more elegant code :) – Gerald Versluis Aug 15 '12 at 07:26
  • Detail "stream not closed" - can other code Open or Delete it ? – H H Aug 15 '12 at 11:33
  • Looking at your code it sounds more the logic part that is at fault, and that its giving up before its done – BugFinder Aug 15 '12 at 11:33
  • As others have suggested, you should try to make your code more robust (e.g. by using `using`). As one more example, the `if (TR != null)` condition is never `false`, because you never reach that code if the ctor of `StreamWriter` above throws (unless of course you set it to `null` somewhere in the code you haven't shown). – Christian.K Aug 15 '12 at 11:56

1 Answers1

1

It sounds like the problem isn't that the streams haven't closed, but rather than the streams may have been closed before they have written. With most stream output you will need to Flush the output stream to ensure that the changes have been written before you Close it. If you don't, then unflushed data will be lost, which sounds very much like what you're seeing.

As Gerald suggested, I would also recommend the

using(var writer = new StreamWriter(@"")
{
    // ...

    writer.Flush();
} 

format, because while it just achieves much the same as try{...}finally{...} it is a little more elegant, and slightly easier to get right.

jgauffin
  • 99,844
  • 45
  • 235
  • 372
David Burton
  • 1,130
  • 10
  • 12