FileStream禁用Close() [英] FileStream disable Close()

查看:261
本文介绍了FileStream禁用Close()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DeleteOnClose选项创建一个临时文件:

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.

但是someObject.WriteDataToFile(fileStream)也会调用fileStream.Close(),这将删除文件,因此我无法检索其内容.

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

问题:如何防止fileStreamsomeObject.WriteDataToFile()中的代码关闭?

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

推荐答案

您可以使用装饰器模式来解决此问题

You could use the decorator pattern to solve this

例如;

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
}

此示例使用自定义方法.您也可以考虑实现IDisposable接口,并在Dispose()上调用Close

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

希望这会有所帮助,

这篇关于FileStream禁用Close()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆