8

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?

Adrian Iftode
  • 15,465
  • 4
  • 48
  • 73
Frosty840
  • 7,965
  • 12
  • 50
  • 86
  • Any chance that in that [Vast amounts of code] region you have a stream of some sort that you haven't closed? – DJ Quimby Feb 08 '12 at 15:32

5 Answers5

17

after mailClient.Send(message); add message.Attachments.Dispose();

This will release the attachment resources

Nasir
  • 171
  • 1
  • 2
8

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);
}
Grant H.
  • 3,689
  • 2
  • 35
  • 53
  • Yup. Manually disposed of all of the mail message's attachments after it was sent. Solved the problem. Thanks. – Frosty840 Feb 08 '12 at 15:44
3

You should use the Using statement when accessing Files. This will dispose of your object and you should be able to call your System.IO.File.Delete()

see here: http://msdn.microsoft.com/en-us/library/htd05whh(v=vs.80).aspx

Seany84
  • 5,526
  • 5
  • 42
  • 67
  • This is the better result...unless you are [for whatever reason] not using as 'using' (then use @Nasir's solution) – Cos Callis Apr 09 '16 at 20:36
1

While I realise the last post on this article was some years ago I thought it worth adding a small amount of additional information for anyone who is unaware...

If you are sending your email asynchronously then you can't use "using" or dispose of anything until the callback fires, instead you should send your MailMessage instance as the UserState parameter of SendAsync(). That way when the callback fires you will be able to dispose of any attachments and the MailMessage instance. You can also Dispose of the Mail Client as it will be the sender object.

Jim
  • 21
  • 1
0

Did you close your attachment file after you've created it?

System.IO.FileStream afile = System.IO.File.Create(@"c:\test\astream.csv");
afile.Close();
afile = null;

See this forum where a similar question has been answered. (It's in C# with asp.net, but it should do the trick when converted to vb.net)

Msonic
  • 1,456
  • 15
  • 25