2009-06-25 1 views
2

У меня возникают проблемы с небольшим количеством кода, который я пишу на C#.Удаление файлов не выполняется с помощью существующего процесса

Я отправляю документ с использованием компонентов MailMessage и SMTP. Я копирую файлы, которые я хочу отправить в каталог temp, такой как c: \ temp, перебирать документы и прикреплять их к письму.

электронная почта посылает штраф, однако при попытке удалить файлы из временной папки, я получаю следующее сообщение об ошибке:

The process can not access the file because it is being used by another process

Я не могу понять, почему это происходит. Ниже приведен код, который обрабатывает документы

public void sendDocument(String email, string barcode, int requestid) 
    { 

     string tempDir = @"c:\temp"; 

     //first we get the document information from the database. 
     Database db = new Database(dbServer, dbName, dbUser, dbPwd); 

     List<Document> documents = db.getDocumentByID(barcode); 
     int count = 0; 
     foreach (Document doc in documents) 
     { 
      string tempPath = tempDir + "\\" + doc.getBarcode() + ".pdf"; 
      string sourcePath = doc.getMachineName() + "\\" + doc.getFilePath() + "\\" + doc.getFileName(); 

      //we now copy the file from the source location to the new target location 
      try 
      { 
       //this copies the file to the folder 
       File.Copy(sourcePath, tempPath, false); 

      } 
      catch (IOException ioe) 
      { 
       count++; 

       //the file has failed to copy so we add a number to the file to make it unique and try 
       //to copy it again. 
       tempPath = tempDir + "\\" + doc.getBarcode() + "-" + count + ".pdf"; 
       File.Copy(sourcePath, tempPath, false); 

      } 

      //we now need to update the filename in the to match the new location 
      doc.setFileName(doc.getBarcode() + ".pdf");     

     } 

     //we now email the document to the user. 
     this.sendEmail(documents, email, null); 

     updateSentDocuments(documents, email); 

     //now we update the request table/ 
     db.updateRequestTable(requestid); 


     //now we clean up the documents from the temp folder. 
     foreach (Document doc in documents) 
     { 
      string path = @"c:\temp\" + doc.getFileName(); 
      File.Delete(path); 
     } 

    } 

Я бы мысли о том, что метод this.sendEmail() будет отправленного по электронной почте, прежде чем вернуться к методу sendDocument, как я думаю, что это объект, который SMTP вызывает удаляется сбой.

Это метод SendEmail:

public void sendEmail(List<Document> documents, String email, string division) 
    { 
     String SMTPServer = null; 
     String SMTPUser = null; 
     String SMTPPwd = null; 
     String sender = ""; 
     String emailMessage = ""; 

     //first we get all the app setting used to send the email to the users 
     Database db = new Database(dbServer, dbName, dbUser, dbPwd); 

     SMTPServer = db.getAppSetting("smtp_server"); 
     SMTPUser = db.getAppSetting("smtp_user"); 
     SMTPPwd = db.getAppSetting("smtp_password"); 
     sender = db.getAppSetting("sender"); 
     emailMessage = db.getAppSetting("bulkmail_message"); 

     DateTime date = DateTime.Now; 

     MailMessage emailMsg = new MailMessage(); 

     emailMsg.To.Add(email); 

     if (division == null) 
     { 
      emailMsg.Subject = "Document(s) Request - " + date.ToString("dd-MM-yyyy"); 
     } 
     else 
     { 
      emailMsg.Subject = division + " Document Request - " + date.ToString("dd-MM-yyyy"); 
     } 

     emailMsg.From = new MailAddress(sender); 
     emailMsg.Body = emailMessage; 

     bool hasAttachements = false; 

     foreach (Document doc in documents) 
     { 

      String filepath = @"c:\temp\" + doc.getFileName(); 

      Attachment data = new Attachment(filepath); 
      emailMsg.Attachments.Add(data); 

      hasAttachements = true; 


     } 

     SmtpClient smtp = new SmtpClient(SMTPServer); 

     //we try and send the email and throw an exception if it all goes tits. 
     try 
     { 
      if (hasAttachements) 
      { 
       smtp.Send(emailMsg); 
      } 
     } 
     catch (Exception ex) 
     { 
      throw new Exception("EmailFailure"); 
     } 


    } 

Как я обойти эту проблему с помощью процесса коробления файл я хочу удалить.

Я могу удалить файл (ы) после завершения работы приложения.

ответ

6

Ты сообщений электронной почты, не удалялись, попробуйте его утилизации после того, как вы отправили его:

try 
{ 
     if (hasAttachements) 
     { 
      smtp.Send(emailMsg);   
     } 
} 
catch ... 
finally 
{ 
     emailMsg.Dispose(); 
} 
1

Первый шаг заключается в том, чтобы выяснить, какой процесс хранится в рассматриваемом файле. Я бы схватил инструментарий SysInternals и использовал команду handle.exe, чтобы определить, какой процесс держит файл.

Не зная, в каком процессе открыт файл, не удастся устранить эту проблему.

Sysinternals Ссылка: http://technet.microsoft.com/en-us/sysinternals/default.aspx

+0

спасибо за ссылку на эти инструменты ... очень полезно ... –

0

Вот трюк я просто discoverred, который, мы надеемся, быть полезным для других людей? Перед добавлением вложений в сообщение создайте вложение в используемой обертке. Это гарантирует, что он будет утилизирован правильно, позволяя удалять файл. Я не уверен, что отправка должна быть в этом цикле; (когда я тестировал, электронные письма не проходили сначала, а через полчаса меня затопило, поэтому решили оставить тестирование на время, когда сеть была немного спокойнее).

using (Attachment attachment = new Attachment(filename)) 
{ 
    message.Attachments.Add(attachment); 
    client.SendAsync(message, string.Empty); 
} 
File.Delete(filename); 

работает хорошо для меня во всяком случае :)

Успехов,

JB

Смежные вопросы