Closing streams, always necessary? .net

后端 未结 4 1277
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 08:54

Is it always necessary to close streams or, because .net is managed code, will it be closed automatically as soon as it drops out of scope (assuming there are no exceptions

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 09:36

    It is good practice to close your streams. Use the using statement, and Dispose() will be called when it falls out of scope (or if an exception is thrown), which will in turn close your stream.

    static string SerialiseObjectToBase64(object obj)
    {
        using (var mstream = new MemoryStream())
        {
            ...
            return Convert.ToBase64String(mstream.ToArray());
        } 
    }
    

提交回复
热议问题