处理临时文件并删除它们

时间:2016-11-13 01:30:22

标签: c# .net winforms file delete-file

我正在使用WinForms。我使用picturebox制作了一个简单的图像查看器应用程序来显示我的图像。我找到了创建临时文件的方法。这些文件始终是图片文件。当我的应用程序使用图像完成时,我希望能够删除位于FormClosing的{​​{1}}文件上的临时文件。要做到这一点,我不能简单地调用File.Delete(C://picture.jpg )因为即使在我的应用程序中显示另一张图片,我的应用程序仍在使用它们。所以我试图处理它,但我无法知道如何做到这一点。我应该使用using语句吗?是否有更好的方法来处理和删除文件,或者有办法使这个工作吗?

C:\Users\taji01\AppData\Local\Temp\8bd93a0dec76473bb82a12488fd350af
  

错误:"进程无法访问文件C:\ picture.jpg,因为它正由另一个进程使用"抛出的执行:' System.IO.IO.Exception'在msconrlib.dll中(进程无法访问文件' C:\ picture.jpg'因为它正在被另一个进程使用")

3 个答案:

答案 0 :(得分:0)

您需要Close() FileStream

答案 1 :(得分:0)

我认为交易经理会做你想做的事。查看.NET Transactional File Manager。当您回滚事务时,它应该自动删除临时文件,只要它们是在事务范围内创建的。

答案 2 :(得分:0)

在这里,你需要处理MailMessage的对象。

For Ex.

// Sends email using SMTP with default network credentials
public static void SendEmailToCustomer(string To, string From, string BCC, string    Subject, string Body, bool IsBodyHtml, string attachedPath = "") {

    //create mail message
    MailMessage message = !string.IsNullOrEmpty(From) ? new MailMessage(From, To) : new MailMessage(From, To);

    //create mail client and send email
    SmtpClient emailClient = new SmtpClient();

    //here write your smtp details below before sending the mail.
    emailClient.Send(message);

    //Here you can dispose it after sending the mail
    message.Dispose();

    //Delete specific file after sending mail to customer
    if (!string.IsNullOrEmpty(attachedPath))
        DeleteAttachedFile(attachedPath);
}

//Method to delete attached file from specific path.
private static void DeleteAttachedFile(string attachedPath) {
    File.SetAttributes(attachedPath, FileAttributes.Normal);
    File.Delete(attachedPath);
}
相关问题