Avoiding dispose of underlying stream

前端 未结 2 849
旧巷少年郎
旧巷少年郎 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:40

    If you subclass the MemoryStream, this will work but you have to call ManualDispose method to close the underlying stream.
    I´m not sure but I think this object will be garbage-collected when it goes out of scope.

    public sealed class ManualMemoryStream : MemoryStream
    {
        protected override void Dispose(bool disposing)
        {
        }
        public void ManualDispose()
        {
            base.Dispose(true);
        }
    }
    

    Edit:
    This is an alternative if you want the MemoryStream to be flushed and ready to be read from top.

    public sealed class ManualMemoryStream : MemoryStream
    {
        protected override void Dispose(bool disposing)
        {
            Flush();
            Seek(0, SeekOrigin.Begin);
        }
        public void ManualDispose()
        {
            base.Dispose(true);
        }
    }
    

提交回复
热议问题