SMTP Send is locking up my files - c#

南楼画角 提交于 2019-11-27 14:58:33

How are you reading the files to create the email message? They should be opened as read-only, with a FileShare set to FileShare.ReadWrite... then they shouldn't be locked. If you are using a FileStream you should also wrap your logic in the using keyword so that the resource is disposed properly.

Update:

I believe disposing the mail message itself will close resources within it and unlock the files:

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

hate answering my own post, but yeah for the next poor guy who has this problem here is the fix:

AFTER YOU SEND THE MESSAGE

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

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

Dispose the attachments... clears the lock, and messages will still be sent with attachments. Dispose DOES NOT delete the files, just clears the attachments :)

Are you closing the files after you finish reading them? If you open them for reading, but don't close them when you're done, it should keep a lock on it until the program exits and automatically closes all the files.

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

I see this a lot when sending attachments. I normally use something like the following:

In the code that moves the files to a different location, you can use the following pattern:

Inside the loop for looping through the files

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!