2014-07-25 71 views
-4

我正在處理一個C#應用程序,它創建一個包含一些數據的文本文件,將其保存在一個文件夾中,將它發送到一個電子郵件地址列表並從該位置刪除該文件但是當我調用File.Delete()時,它會引發一個異常,說明文件無法訪問,因爲它正在被另一個進程使用。這是因爲該文件正在使用的電子郵件服務,並試圖刪除的話,它的一個明顯的例外,但是當我試圖給兩個函數調用之間的延遲,它仍然把我異常從文件夾中刪除文本文件時出錯

_dailyBargainReport.sendRejectionReport(servername, fromAddress, password, sub, bodyofmail, rejectionReportPath); 

      Task.Delay(20000); 
      File.Delete(rejectionReportPath); 
+2

我會假設'sendRejectionReport'裏面沒有using語句。實現'IDisposable'的所有東西都需要用using語句包裝。 – ChaosPandion

+0

'.sendRejectionReport'看起來像什麼?它是異步的嗎? –

+0

請顯示您正在使用的代碼來創建文件 – faby

回答

1

我覺得你的問題是,你是不是調用Dispose方法使用statment隨時撥打DisposeFileStream

using (FileStream f = File.Open("example.txt", FileMode.Open, FileAccess.Read, FileShare.None)) 
{ 
    //do your operations 
} 
File.Delete(rejectionReportPath); 

所以相當於

try{ 
    FileStream f = File.Open("example.txt", FileMode.Open, FileAccess.Read, FileShare.None); 
} 
finally{ 
    ((IDisposable)f).Dispose(); 
} 
//delete file here 

更新

試試這種方式等待功能

Task.Factory.StartNew(() => 
    { 
     _dailyBargainReport.sendRejectionReport(servername, fromAddress, password, sub, bodyofmail, rejectionReportPath); 
    }) 
    .ContinueWith(() => 
    { 
     File.Delete(rejectionReportPath); 
    }).Wait(); 

這樣你確信Delete功能的sendRejectionReport結束後調用。
記住撥打Dispose裏面函數

+0

這樣的東西來打包一個bandaid它不是因爲打開文件,而是因爲正在使用sendRejectionReport函數 – DoIt

+0

我已更新我的答案 – faby

+0

使用新的更新答案,它既不發送電子郵件也不刪除文件 – DoIt