简体   繁体   中英

How do I force write to file using StreamWriter?

I always use streamwriter writer = new StreamWriter(file) to write to file. The problem is it wont actually write to file until writer.close() .

If between class create and class close something bad happens (and the program never reaches writer close), I wont get any information in the file. How to force write between create and close?

Make sure you have your code wrapped in a using statement:

using (var writer = new StreamWriter(file))
{
    // do your writing
}

This will help "clean up" by disposing (and flushing and closing) the stream for you, such as in situations where Close() would not get called if an unhandled exception were to be thrown after instantiation of the stream. The above is basically equivalent to:

{
    var writer = new StreamWriter(file);
    try
    {
        // do your writing
    }
    finally
    {
        if (writer != null)
            ((IDisposable)writer).Dispose();
    }
}

Note: anything that implements the IDisposable interface should be used within a using block to make sure that it is properly disposed.

If it's important that any pending writes actually be written out to disk before the writer is closed, you can use Flush .

Having said that, it sounds like your real problem is that you're not closing your writer when you should be, at least under certain circumstances. You should be closing the writer no matter what once you're done writing to it (even in the event of an exception). You can use a using (or an explicit try/finally block, if you want) to ensure that the writer is always closed.

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