Dispose of the MailMessage when you're done with it.
It still has a lock on the file you've added as an attachment until you've done so.
var filePath = "C:\path\to\file.txt";
var smtpClient = new SmtpClient("mailhost");
using (var message = new MailMessage())
{
message.To.Add("[email protected]");
message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.SubjectEncoding = Encoding.UTF8;
message.Body = "Test " + DateTime.Now;
message.Attachments.Add(new Attachment(filePath));
}
if (File.Exists(filePath)) File.Delete(filePath);
Console.WriteLine(File.Exists(filePath));
Output: False
I would imagine that if you still have something locking the file after disposing the message, that you likely have another lock on the file, but without code, we can't help you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…