问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/23479952/how-do-i-force-write-to-file-using-streamwriter