FileOptions.DeleteOnClose
will cause the file to be deleted automatically when closed. This also works if the program is terminated by an exception.
For example, as mentioned in this answer:
using (FileStream fs = new FileStream(Path.GetTempPath() + "foo.bar",
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None,
4096, FileOptions.RandomAccess | FileOptions.DeleteOnClose))
{
// temp file exists
}
// temp file is gone
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…