2016-11-13 26 views
0

我正在使用WinForms。我使用picturebox制作了一个简单的图像查看器应用程序来显示我的图像。我创建了一个创建临时文件的方法。这些文件总是图片文件。当我的应用程序完成使用图像我想要能够删除这些临时的FormClosing文件位于:C:\Users\taji01\AppData\Local\Temp\8bd93a0dec76473bb82a12488fd350af要做到这一点,我不能简单地调用File.Delete(C://picture.jpg),因为我的应用程序仍在使用它们即使在我的应用程序中显示了另一张照片。所以我试图摆脱它,但我无法想象如何做到这一点。我应该使用使用声明吗?有没有更好的方式来处理和删除文件或有办法使这项工作?处理临时文件并删除它们

_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); 

Error: "The process cannot access the file C:\picture.jpg because it is being used by another process" Exeption thrown: 'System.IO.IO.Exception' in msconrlib.dll (The process cannot access the file 'C:\picture.jpg' because it is being used by another procesas")

+0

'Path.GetTempFileName()' – SLaks

+0

https://msdn.microsoft.com/en-us/library/system.io.filestream(v=vs.110).aspx#Examples – Jim

+0

从[文件为Image.FromFile()'](https://msdn.microsoft.com/en-us/library/stf701f5(v = vs.110).aspx):*该文件保持锁定状态,直到图像被丢弃。 *所以你必须首先处理图像。或者在内存中复制并处理原件。请参阅http://stackoverflow.com/questions/6576341/open-image-from-file-then-release-lock – dbc

回答

0

您需要Close()FileStream

+0

我是否在formclosing或在使用它的方法中关闭它? – taji01

+1

只要不再需要,你应该尽快结束。 – SLaks

+1

['Image.FromStream()'](https://msdn.microsoft.com/en-us/library/93z9ee4x(v = vs.110).aspx)要求流在整个生命周期中保持打开状态图片。如果您手动处理文件流,则会导致问题出现,例如无法保存图像。见http://stackoverflow.com/questions/1053052/a-generic-error-occurred-in-gdi-jpeg-image-to-memorystream – dbc

0

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

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); 
}