3

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

我正在使用 MailMessage 和 SMTP 组件发送文档。我将希望发送的文件复制到临时目录,例如 c:\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");
        }


    }

如何通过占用我要删除的文件的进程来解决这个问题。

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

4

3 回答 3

6

您的电子邮件没有被处理,请在发送后尝试处理它:

 try
 {
      if (hasAttachements)
      {
          smtp.Send(emailMsg);         
      }
 }  
 catch ...
 finally
 {
      emailMsg.Dispose();
 }
于 2009-06-25T15:03:01.860 回答
1

第一步是弄清楚什么进程正在保存有问题的文件。我会抓住 SysInternals 工具包并使用 handle.exe 命令来确定哪个进程正在保存文件。

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

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

于 2009-06-25T14:58:39.047 回答
0

这是我刚刚发现的一个技巧,希望对其他人有用吗?在向邮件添加附件之前,请在 using 包装器中创建附件。这样可以确保正确处理它,从而成功删除文件。我不确定发送是否也需要在这个循环中;(我测试的时候,一开始邮件打不通,然后半小时后我就被淹了,所以决定等网络稍微平静一些后再测试)。

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

无论如何对我来说都可以:)

祝你好运,

JB

于 2010-06-08T22:02:41.460 回答