简体   繁体   中英

How can I close the TextWriter stream on Windows XP successfully?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM