2015-07-21 44 views
0

我有一個windows服務,它定期從表中提取數據並創建excel文件並將其郵寄給用戶。發送郵件後,我需要刪除該文件。已使用以下代碼:當試圖刪除文件時正在使用'文件正在使用'#

public void LABInstrumentExcelGeneration(string filePath) { 
    try { 
     string connectionString = GetConnectionString(filePath); 

     List <LABInstruments> listLABInstrument = null; 
     listLABInstrument = new List <LABInstruments>(); 
     listLABInstrument = LABInstrumentBL.GetLABInstrumentList(); 
     if (listLABInstrument.Count > 0) { 
      using(OleDbConnection conn = new OleDbConnection(connectionString)) { 
       conn.Open(); 
       OleDbCommand cmd = new OleDbCommand(); 
       cmd.Connection = conn; 

       cmd.CommandText = "CREATE TABLE [table2] (SrNo string,CalibrationDoneOn Date);"; 
       cmd.ExecuteNonQuery(); 

       foreach(LABInstruments tc1 in listLABInstrument) { 
        cmd.CommandText = "INSERT INTO [table2](SrNo,CalibrationDoneOn) VALUES('" + tc1.SrNo + "','" + tc1.CalibrationDoneOn + "');"; 
        cmd.ExecuteNonQuery(); 

       } 
       conn.Close(); 
       conn.Dispose(); 
      } 
     } 
    } catch (Exception ex) {} 
} 

SendMail(filePath, role); 

if (File.Exists(filePath)) { 
    File.Delete(filePath); 
    eLog.WriteEntry("file deleted"); 
} 

但它給出錯誤文件正被另一個進程使用。 何可以刪除文件嗎?而且,我使用OLEDB創建文件。是否有任何其他文件創建的最佳做法?已經嘗試過ExcelLibrary,但在其中創建的文件不適用於所有版本的辦公室,因此放棄了它。

+0

你並不需要使用'conn.Close()'和'conn.Dispose();'因爲該對象將由於使用塊而自動處理。同時使用參數化查詢來避免sql注入 – Izzy

+0

當你的服務創建這些文件時,你在創建之後確保File.Close()嗎? – uk2k05

+0

我沒有明確地打開該文件,因此不需要file.Close()。 – Priya

回答

2

試試這個:

protected virtual bool IsLocked(FileInfo fileName) 
{ 
    FileStream fStream = null; 
    try 
    { 
     fStream = fileName.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
    } 
    catch (IOException) 
    { 
     return true; 
    } 
    finally 
    { 
     if (fStream != null) 
     { 
      fStream.Close(); 
     } 
    } 
    return false; 
} 

然後:

if (File.Exists(filePath)) 
{ 
    FileInfo myfile = new FileInfo(filePath); 
    if(IsLocked(myfile)) 
    { 
     File.Create(filePath).Close(); 
     File.Delete(filePath); 
     eLog.WriteEntry("file deleted"); 
    } 
    else 
    { 
     File.Delete(filePath); 
     eLog.WriteEntry("file deleted"); 
    } 
} 
1

我認爲這個問題可能是sendmail的返回之前,它已經使用完文件。

相反的sendmail()我用這個功能,釋放了要刪除的文件:

public static void send(string subject, string body, string from, string to, List<string> attachments = null) 
    { 
     using (MailMessage message = new MailMessage(new MailAddress(from), new MailAddress(to))) 
     { 
      message.Subject = subject; 
      message.Body = body; 
      if (attachments != null && attachments.Count > 0) 
      { 
       foreach (string s in attachments) 
       {       
        if (s != null) 
        { 
         /* this code fixes the error where the attached file is 
         * prepended with the path of the file */ 
         Attachment attachment = new Attachment(s, MediaTypeNames.Application.Octet); 
         ContentDisposition disposition = attachment.ContentDisposition; 
         disposition.CreationDate = File.GetCreationTime(s); 
         disposition.ModificationDate = File.GetLastWriteTime(s); 
         disposition.ReadDate = File.GetLastAccessTime(s); 
         disposition.FileName = Path.GetFileName(s); 
         disposition.Size = new FileInfo(s).Length; 
         disposition.DispositionType = DispositionTypeNames.Attachment; 
         message.Attachments.Add(attachment); 
        } 
       } 
      } 
      using (SmtpClient client = new SmtpClient()) 
      { 
       client.Send(message); 
      } 
     } 
    }