1

使用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在程序关闭时显式调用。

4

0 回答 0