Hi all
In the following Sub I'm sending an Attachment when the email has been sent I would like to delete the attachment but I get an system.IO.IOException Error. the file I'm trying to delete is being used by another process.
How can I detect if the process has finished.

Thanks
Happy New Year to everyone

Private Sub SendMail()
        Try
            Dim cfiAttach As Net.Mail.Attachment
            Dim Attacmentfile As String = AttDir & fileName & ".pdf"
            Dim SmtpServer As New SmtpClient()
            Dim mail As New MailMessage()
            SmtpServer.Credentials = New Net.NetworkCredential(diaSettings.txtMail_User.Text, diaSettings.txtMail_Pass.Text)
            SmtpServer.Port = smtpPrt
            SmtpServer.Host = SmtpHst
            mail = New MailMessage()
            mail.From = New MailAddress(Mail_user)
            mail.To.Add(Mail_TO)
            ' mail.Bcc.Add(BBC_MailTO)
            mail.Subject = fileName
            mail.Body = ""
            cfiAttach = New Attachment(Attacmentfile)
            If File.Exists(Attacmentfile) Then
                cfiAttach = New Attachment(Attacmentfile)
                mail.Attachments.Add(cfiAttach)
            Else
                MsgBox("Attachment Not Found")
            End If
            SmtpServer.Send(mail)
            MsgBox("Sent")
           [U]System.IO.File.Delete(AttDir & fileName & ".pdf")[/U] 
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

Thanks thines01 for your reply
I added the line of code you specified right after the email was sent but I still get
the system.IO.IOException.
I also tried mail.Attachments.Dispose() and no luck.

You called the dispose BEFORE attempting the delete?
Also, if you Catch the exception, what is the exception message (the actual error)?

Yes the Dispose was called before attempting the delete.
This is the actual error:
System.IO.IOException: The process cannot access the file 'C:\CFI\33Glasgow.pdf'
because it is being use by another process.
at System.IO._error.winIOErroe(Int32 errorCode.String maybeFullPath)
at System.IO.File.Delete(String Path)
at CFI.Cfi_Report.SendMail() in C:\Users\Admin\Documents\Visual Studio 2010\CFI\Cfi_Report.vb:Line106

The next thing I would check is to make sure the .pdf is not open anywhere else and see if pausing for 10 seconds before the actual delete will give the system time to release the resource.

Also, did you notice you're calling New Attachment(Attacmentfile) twice?

Thanks you solved it.
Removing the First call for New Attachment(Attacmentfile)did the trick.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.