FileStream disable Close()

你离开我真会死。 提交于 2019-12-12 06:47:19

问题


I'm creating a temporary file with the DeleteOnClose option:

var fileStream = File.Create(Path.GetTempFileName(), 4096, FileOptions.DeleteOnClose);

Another class(which I cannot modify) will write some data to this file:

someObject.WriteDataToFile(fileStream);

then I want to retrieve the data for further processing, close the stream, and let the file be automatically deleted.

But someObject.WriteDataToFile(fileStream) also calls fileStream.Close(), which will delete the file, so I cannot retrieve its contents.

Question: How can I keep fileStream from being closed by the code in someObject.WriteDataToFile() ?


回答1:


You could use the decorator pattern to solve this

e.g;

public class UnclosableFileStream : StreamDecorator
{
    public UnclosableFileStream(Stream original) : base(original)
    {

    }

    public override void Close()
    {

    }

    public void RealClose()
    {
        base.Close();
    }
}

public abstract class StreamDecorator : Stream
{
     .... implements Stream base case
}

This example uses a custom method. You could also consider implementing the IDisposable interface and call Close on Dispose()

Hope this helps,



来源:https://stackoverflow.com/questions/20097577/filestream-disable-close

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!