2016-11-13 76 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); 
}