Avoiding dispose of underlying stream

前端 未结 2 835
旧巷少年郎
旧巷少年郎 2021-01-03 02:39

I\'m attempting to mock some file operations. In the \"real\" object I have:

StreamWriter createFile( string name )
{
  return new StreamWriter( Path.Combine         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 03:26

    The nature of the StreamWriter is to dispose the underlying stream when it is itself disposed. However, by creating (and returning) a sub-class of StreamWriter (I'm going to call it LeakyStreamWriter), you should be able to prevent this default behaviour.

    public class LeakyStreamWriter : StreamWriter
    {
        public override void Close()
        {
            BaseStream.Close(); //close, but do not dispose
        }
    
        protected override void Dispose(bool disposing)
        {
            //do nothing here
        }
    }
    

    Note that I am making the assumption that the StreamWriter has no other components to dispose other than the underlying stream, you may want to check the dissassembly of the StreamWriter to check what is actually done in those two methods.

    Anyway, the result of using the above subclass is that the underlying stream will be closed, but not disposed, when the streamwriter is closed.

提交回复
热议问题