FileOptions.DeleteOnCloseを使用すると、最後のハンドルが閉じられたときにファイル自体を削除できます。これは、プログラムを閉じたときに一時ファイルを削除する場合に非常に便利です。次の関数を作成しました
/// <summary>
/// Create a file in the temp directory that will be automatically deleted when the program is closed
/// </summary>
/// <param name="filename">The name of the file</param>
/// <param name="file">The data to write out to the file</param>
/// <returns>A file stream that must be kept in scope or the file will be deleted.</returns>
private static FileStream CreateAutoDeleteFile(string filename, byte[] file)
{
//get the GUID for this assembly.
var attribute = (GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0];
var assemblyGuid = attribute.Value;
//Create the folder for the files to be saved in.
string folder = Path.Combine(Path.GetTempPath(), assemblyGuid);
Directory.CreateDirectory(folder);
var fs = new FileStream(Path.Combine(folder, filename), FileMode.OpenOrCreate, FileAccess.ReadWrite,
FileShare.ReadWrite, 16 << 10, //16k buffer
FileOptions.DeleteOnClose);
//Check and see if the file has already been created, if not write it out.
if (fs.Length == 0)
{
fs.Write(file, 0, file.Length);
fs.Flush();
}
return fs;
}
すべてが完全に機能しますが、users フォルダーに残りのフォルダーを残し%TEMP%
ます。私は善良な市民になりたいし、終わったらフォルダも削除したいのですが、ファイルのようにそれを行う方法はないと思います.
ファイルを削除するようにフォルダーを自動削除する方法はありますか、それともフォルダーをそのままにしておくかDirectory.Delete
、プログラムを閉じるときに明示的に呼び出す必要があります。