Frosty840 Frosty840 - 1 month ago 6
Vb.net Question

File appears to be held open after being sent as an attachment by SmtpClient. How can I delete the file?

I have a number of files that are generated in a function defined as:

Public Function GeneratePDF(exportFileName As String) As String
Dim GeneratePath As String = FileSystem.CombinePath(standardDirectory, exportFileName & DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") & ".pdf")
If GenerateFile(GeneratePath) Then
Return GeneratePath
End If
Return String.Empty
End Function


These files are immediately printed and the files are automatically saved to a directory; the files themselves are not for use by the actual software users. I timestamp the files to keep them uniquely identified for auditing purposes.

I've now received a requirement to email some of these files externally to the company, and someone has complained that the current filenames are not user-friendly.

So, I tried copying the generated file to a temp directory, with a friendlier name, emailing the friendlier file, then deleting it, leaving my audit trail intact, like so:

Public Function GeneratePDF(exportFileName As String) As String
Dim GeneratePath As String = FileSystem.CombinePath(standardDirectory, exportFileName & DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") & ".pdf")
If GenerateFile(GeneratePath) Then

Dim friendlyFilePath As String = FileSystem.CombinePath(standardDirectory, GetFriendlyFileName(GeneratePath))
System.IO.File.Copy(GeneratePath, friendlyFilePath)

Dim mailMsg As New System.Net.Mail.MailMessage
Dim smtp As New System.Net.Mail.SmtpClient
[Vast amount of code, which attaches friendlyFilePath to the email, then sends it]

System.IO.File.Delete(friendlyFilePath)

Return GeneratePath
End If
Return String.Empty
End Function


This throws a
System.IO.IOException
on the line
System.IO.File.Delete(friendlyFilePath)
because the file is still in use, after it has been emailed.

I've taken out the email code, which makes the copying and deleting work fine, so it's apparently attaching the file to the email which causes the problem.

I've also tried breakpointing before the delete line, waiting five minutes, confirming the email has been sent, then advancing the code, but the same exception is still thrown.

Can anyone suggest how to resolve this issue?

Answer

The SmtpClient does not release the handle to an attachment. You will have to handle that manually, or, what I do, is copy the file contents to a MemoryStream first. The code below should work as well.

using (MailMessage message = new MailMessage(from, to, subject, body))
using (Attachment attachment = new Attachment(fileName))
{
   message.Attachments.Add(attachment);
   mailClient.UseDefaultCredentials = true;
   mailClient.Send(message);
}