I am writing a program that creates a file and attaches it to an email. I use a loop to create the attachment, send the email and then do it again with different information in the attachment.
This works well for one tim through the loop, but on the second time through I get an error when I try to open the file for output to create the new version of the file. I get an unhandled exception of "The process cannot access the file 'c:\Project\Articles1\Article.txt' because it is being used by another process.". How can I release the file from being used once the email has been sent?

My code looks like this:

[
For I = 0 To NumEntries - 1
FileName = "c:\Project\Articles1\Article.txt"
Flag = 1
FileOpen(1, FileName, OpenMode.Output)
For J = 0 To 7
WriteLine(1, files(I, J))
Next J
FileClose(1)
Attachment = "C:\Project\Articles1\Article.txt"
Signature = files(I, 7)
Message = "XXX"
If Flag = 1 Then
Call sendMail(Message, FileName)


End If
Next I


End Sub
Private Sub sendMail(ByRef Message, ByRef FileName)
Dim Attach As Attachment
Attach = New Attachment(FileName)
'create the mail message
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("XXX.XXX")
mail.To.Add("XXX.XXX")
'set the content
mail.Subject = "Article to be submitted."
mail.Body = Message
mail.Attachments.Add(Attach)
mail.IsBodyHtml = True

'send the message
Dim smtp As New SmtpClient("XXX.XXX")
smtp.Port = 25
smtp.EnableSsl = True
smtp.Credentials = New System.Net.NetworkCredential("XXX", "XXX")
smtp.Send(mail)


End Sub
]

smtp.Send(mail) doeasn't mean the mail sending is already done.
Try this:

Dim smtp As New SmtpClient("XXX.XXX")
AddHandler smtp.SendCompleted, AddressOf Send_Completed 'catch up when the mail  is completed
smtp.Port = 25
smtp.EnableSsl = True
smtp.Credentials = New System.Net.NetworkCredential("XXX", "XXX")
smtp.Send(mail)

and add this

Private Sub Send_Completed(ByVal sender As Object, ByVal e As ComponentModel.AsyncCompletedEventArgs)
		'do what you want when mail is finished
	End Sub
This question has already been answered. Start a new discussion instead.