Reputation: 4249
I have an ASP .Net Core 2.2 Web API. In it, I have a controller that's used by the front end to send emails. It's using System.Net.Mail. I've simplified the code as much as possible:
//POST: api/Email
[HttpPost]
public async Task<IActionResult> Post()
{
string attachment1 = Path.Combine(System.AppContext.BaseDirectory, "Attachments", "a.pdf");
string attachment2 = Path.Combine(System.AppContext.BaseDirectory, "Attachments", "b.pdf");
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.Attachments.Add(new Attachment(attachment1));
mailMessage.Attachments.Add(new Attachment(attachment2));
mailMessage.To.Add("[email protected]");
using (var smtpClient = new SmtpClient("smtp.gmail.com", 578))
{
smtpClient.Credentials = new NetworkCredential("[email protected]", "12345");
smtpClient.EnableSsl = true;
await smtpClient.SendMailAsync(mailMessage);
}
}
File.Delete(attachment1);
File.Delete(attachment2);
return Ok();
}
When I try to delete the attachments, I get the following error:
Error: The process cannot access the file 'C:\Users\fabsr\source\repos\PropWorx.API\PropWorx.API\bin\Debug\netcoreapp2.2\Attachments\a.pdf' because it is being used by another process.
I've tried adding this just before the delete lines:
foreach (var attachment in mailMessage.Attachments)
attachment.Dispose();
Even though, from what I've read, disposing the MailMessage will also dispose the attachments. However, it didn't help. Any ideas? Indeed if I try to delete the file from Explorer it also tell me the file is in use. Only once I kill the running project (by hitting the STOP button in Visual Studio) can I then delete the files.
P.s. I haven't tested this on the live server yet... currently I'm testing this on my workstation, running in Debug mode in Visual Studio 2017, if that makes a difference...
Upvotes: 0
Views: 753
Reputation: 4249
After reading Daniel's comment, I took the attachments out of the running folder (where the API was running) an now it's fine. It looks like Visual Studio was locking these files, even though they were not part of my project, and didn't even appear in my Solution Explorer.
Upvotes: 0
Reputation: 1651
Add the attachments during the using
//POST: api/Email
[HttpPost]
public async Task<IActionResult> Post()
{
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.Attachments.Add(new Attachment(@"C:\a.pdf"));
mailMessage.Attachments.Add(new Attachment(@"C:\b.pdf"));
mailMessage.To.Add("[email protected]");
using (var smtpClient = new SmtpClient("smtp.gmail.com", 578))
{
smtpClient.Credentials = new NetworkCredential("[email protected]", "12345");
smtpClient.EnableSsl = true;
await smtpClient.SendMailAsync(mailMessage);
}
}
File.Delete(@"C:\a.pdf");
File.Delete(@"C:\b.pdf");
return Ok();
}
Upvotes: 1