使用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;
}
一切正常但我在用户%TEMP%
文件夹中留下了一个剩余的文件夹。我想成为一个好公民,并在完成后删除文件夹,但我认为没有办法像我对文件那样做。
有没有办法自动删除文件夹,就像删除文件一样,或者我只需要使用剩余的文件夹,或者在我的程序关闭时必须显式调用Directory.Delete
。