SMTP发送正在锁定我的文件 – c#

我有一个function,发送消息(很多)和他们的附件。

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

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

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

更新:

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

 using (var mail = new MailMessage()) { AddAttachments(mail); } // File copy code should work here 

讨厌回答我自己的post,但是对于下一个有这个问题的穷人来说是修复:

你发送消息之后

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

处理附件…清除锁定,消息仍将与附件一起发送。 处置不删除文件,只清除附件:)

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

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

发送附件时我看到了很多。 我通常使用以下内容:

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

循环内部循环文件

 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. } }