问题
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