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?