Scenario: you need to store a large block of data, e.g. as the result of an XSL transformation on an XML document. Using a MemoryStream would simply kill your server/application since it would use too much memory. Using a FileStream can be a but tedious since it would require write permissions on a specific folder…
Wait, doesn’t this sound just like a temporary file, i.e. storing a file in the TEMP path.
Yes, it does – and a simple solution is actually just to use a FileStream with a twist:
{
public TempFileStream()
: base(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite)
{
}
public override void Close()
{
base.Close();
if (File.Exists(Name))
{
File.Delete(Name);
}
}
}
Here we simply create a new temporary file with R/W access. In the Close method of the FileStream we simply delete the file. Nice and simple and your temporary file only "lives" during your "using" statement…
