Do I need to dispose the FileStream object?

后端 未结 3 2089
我寻月下人不归
我寻月下人不归 2020-12-11 18:02

I am pretty depressed by my programming knowledge but do we really need to dispose FileStream Object ?

Reason I am asking is because code is throwing \"File being us

3条回答
  •  遥遥无期
    2020-12-11 18:41

    If a class implements IDisposable, then you should dispose it so any resources gets closed/cleaned up asap instead of relying on the garbage collector. Better yet, wrap it in a using block so it gets closed even if an exception occurs.

    using (var stream = new FileStream(...))
    {
       // do stuff with stream
    }
    

提交回复
热议问题