26

我有一个发送消息(很多)及其附件的功能。

它基本上遍历目录结构并从文件结构创建电子邮件,例如

 c:\emails\message01
                \attachments
 c:\emails\message02
                \attachments

使用标准的 .net c# 来创建消息。

在创建所有消息之后...我有另一个函数可以在之后直接运行,它将消息文件夹复制到另一个位置。

问题是 - 文件被锁定......

注意:我没有移动文件,只是复制它们......

关于如何使用 c# 复制锁定文件的任何建议?

更新

我有这个添加附件的方法

    private void AddAttachments(MailMessage mail)
    {
        string attachmentDirectoryPath = "c:\messages\message1";
        DirectoryInfo attachmentDirectory = new DirectoryInfo(attachmentDirectoryPath);
        FileInfo[] attachments = attachmentDirectory.GetFiles();
        foreach (FileInfo attachment in attachments)
        {
            mail.Attachments.Add(new Attachment(attachment.FullName));
        }
    }
4

5 回答 5

58

您如何阅读文件以创建电子邮件?它们应该以只读方式打开,并FileShare设置为FileShare.ReadWrite... 然后它们不应该被锁定。如果您使用的是 aFileStream您还应该将您的逻辑包装在using关键字中,以便正确处理资源。

更新:

我相信处理邮件本身会关闭其中的资源并解锁文件:

using (var mail = new MailMessage())
{
    AddAttachments(mail);
}
// File copy code should work here
于 2009-08-18T20:46:58.877 回答
21

讨厌回答我自己的帖子,但是对于下一个遇到此问题的可怜人来说,解决方法是:

发送信息后

        // Send the mail
        client.Send(message);

        //Clean up attachments
        foreach (Attachment attachment in message.Attachments)
        {
            attachment.Dispose();
        }

处理附件... 清除锁定,邮件仍将与附件一起发送。Dispose 不会删除文件,只会清除附件 :)

于 2009-08-18T21:14:25.483 回答
3

阅读完文件后是否要关闭文件?如果您打开它们进行阅读,但完成后不关闭它们,它应该保持锁定,直到程序退出并自动关闭所有文件。

于 2009-08-18T20:48:00.780 回答
2
    MailMessage email = new MailMessage();

    email.From = txtFrom.Text;
    email.To = txtToEmail.Text;
    email.Subject = txtMSubject.Text; 
    email.Body = txtBody.Text;

    SmtpClient mailClient = new SmtpClient();
    mailClient.Host = "smtp.emailAddress";
    mailClient.Port = 2525;
    mailClient.Send(email );
    email.Dispose();

    // After Disposing the email object you can call file delete

    if (filePath != "")
    {
      if (System.IO.File.Exists(filePath))
      {
        System.IO.File.Delete(filePath); 
      }
    }
于 2012-06-26T00:00:26.787 回答
0

我在发送附件时经常看到这种情况。我通常使用以下内容:

在将文件移动到不同位置的代码中,您可以使用以下模式:

在循环内循环文件

bool FileOk = false;
while (!FileOk)
{
   try
   {
      // code to move the file
      FileOk = true;
   }
   catch(Exception)
   {
      // do nothing or write some code to pause the thread for a few seconds.
   }

}
于 2009-08-18T20:51:13.283 回答