开发者

Force close a stream

I have an issue from time to time, I have a few StreamReaders and StreamWriters in my program that read info and write it. They go right about 99% of the time, but once in a while I end up with a StreamWriter that won't close, on a piece of code I've run multiple times.

This tends to happen if I spam a function, but I am trying to find a safe way to guarantee a steam dispose开发者_如何转开发d. Anyone know how?


try a using statement MSDN

using (StreamWriter stream = new StreamWriter(Initialization)){

   //your code

}

this can be useful:

Closing Stream Read and Stream Writer when the form exits

Also you could use a Try Block

try
{
    //Declare your streamwriter
    StreamWriter sw = new StreamWriter(Initialization);
}
catch
{
    //Handle the errors
}
finally
{
    sw.Dispose();
}


If the stream's scope is local, always use the following construct:

using (var stream = new Stream())
{
    ...do stream work here...
}

If on the other hand you are using the stream as a class field then implement the IDisposable pattern and dispose your stream objects when disposing your class: IDisposable


Wrapping the StreamWriter in a using statement is how I usually ensure it is disposed of.

using (var writer = new StreamWriter(@"C:\AFile.txt"))
{
    //do some stuff with writer
}

An alternative would be to use a finally block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜