删除文件会因现有进程而失败

时间:2009-06-25 14:56:09

标签: c# email delete-file

我遇到了一些我用C#编写的代码问题。

我正在使用MailMessage和SMTP组件发送文档。我将我希望发送的文件复制到临时目录,例如c:\ temp,遍历文档并将它们附加到电子邮件中。

电子邮件发送正常,但是当我尝试从temp目录中删除文件时,出现以下错误:

  

该进程无法访问该文件,因为该文件正由另一个进程

使用

我无法理解为什么会这样。以下是处理文档的代码

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


    }

如何通过占用我希望删除的文件的进程解决此问题。

我可以在应用程序完成后删除文件。

3 个答案:

答案 0 :(得分:6)

您的电子邮件未被处置,请在发送后尝试处理:

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

答案 1 :(得分:1)

第一步是弄清楚有问题的文件中包含哪些进程。我会抓住SysInternals工具包并使用handle.exe命令来确定保留文件的进程。

在不知道文件打开的进程的情况下,无法解决此问题。

Sysinternals链接:http://technet.microsoft.com/en-us/sysinternals/default.aspx

答案 2 :(得分:0)

这是我刚刚发现的一个技巧,希望对其他人有用吗? 在向邮件添加附件之前,请在using wrapper中创建附件。这可以确保它被正确处理,从而允许成功删除文件。我不确定发送是否也需要在这个循环中; (当我测试时,电子邮件最初没有通过,半小时后我被淹没了,所以决定在网络稍微平静的时候离开测试。)

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

无论如何,对我来说还可以。)

祝你好运,

JB