【问题标题】:Disposing Temp Files and Deleting them处理临时文件并删除它们
【发布时间】:2016-11-20 22:46:26
【问题描述】:

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

  _fileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
  File.Copy(imagePath, _fileName);
  _stream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileOptions.DeleteOnClose);
  this._Source = Image.FromStream(_stream);

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

【问题讨论】:

  • Path.GetTempFileName()
  • 来自docs for Image.FromFile()文件保持锁定直到图像被释放。所以你必须先释放图像。或者在内存中制作一份副本并丢弃原件。见stackoverflow.com/questions/6576341/…
  • 来自Image.FromStream() 的文档:您必须在图像的生命周期内保持流打开。
  • 这里的问题不止一个。但请注意异常消息,它不是在谈论临时文件。 C:\picture.jpg 只能是 imagePath,不能是 _fileName。因此,您在 magePath 上做错了我们看不到的其他事情。只需积极地解决这个问题,忘记临时文件,因为它们没有解决任何问题。在分配_Source 之前,您可能不再需要旧的了,因此请丢弃它。或者,如果您无法弄清楚,则通过使用 Bitmap(Image) 构造函数创建内存中的副本来避免所有锁定,以便您可以立即处理。

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


【解决方案1】:

你需要Close()你的FileStream

【讨论】:

  • 我是在表单关闭中关闭它还是在我使用它的方法中关闭它?
  • 您应该在不再需要它们时立即关闭它们。
  • Image.FromStream() 要求流在图像的生命周期内保持打开状态。如果您手动处理文件流,则会导致问题,例如无法保存图像。见stackoverflow.com/questions/1053052/…
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    这里需要配置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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-14
      • 2012-04-12
      • 2010-09-24
      • 1970-01-01
      • 2011-07-12
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多