This is an interesting idea, but there's something about this design that troubles me. Forgive me if you've already addressed this in your design. But if your design is just a simple wrapper around FileStream
, there's a subtle but, I think, significant problem.
If you're deleting the file when the stream is closed, that means that the only way to actually use the data in the file is if the FileAccess
is ReadWrite
. Correct? In other words, you'll be using the file with code that looks like this:
using (TempFileStream t as new TempFileStream())
{
WriteDataToTempFile(t);
t.Seek(0, SeekOrigin.Begin);
ReadDataFromTempFile(t);
}
The problem I see is that ReadDataFromTempFile
is expecting the file to be opened for read access, not read/write access. And this opens the door for some bugs that I think will be very hard to find. Consider code like this:
using (TempFileStream t as new TempFileStream())
{
MyClass o = new MyClass(o);
o.TempStream = t;
o.ProduceOutput();
t.Seek(0, SeekOrigin.Begin);
o.ProcessOutput();
}
...when compared with this:
MyClass o = new MyClass();
string n = Path.GetTempFileName();
using (FileStream s = new FileStream(n, FileMode.Create, FileAccess.Write))
{
o.TempStream = t;
o.ProduceOutput();
}
using (FileStream s = new FileStream(n, FileMode.Open, FileAccess.Read))
{
o.TempStream = t;
o.ProcessOutput();
}
File.Delete(n);
Sure, the first method is shorter than the second. But the second method will throw an exception if ProcessOutput
calls a method that writes to TempStream
. (Or sets a property whose set accessor raises an event whose event handler dispatches a call to a method that writes to TempStream
, which how this problem will probably end up happening.) The first one will just produce unexpected results for no apparent reason.
You can get around this, I think, by having your TempFileStream
class open the underlying FileStream
using FileAccess.Write
. Then implement a Rewind
method that closes this FileStream
and creates a new one that uses FileAccess.Read
. If you do that, any method that tries to write to the file while it's opened for read access (or vice versa) will at least throw an exception.