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
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")
'set the content
mail.Subject = "Article to be submitted."
mail.Body = Message
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")

End Sub

6 Years
Discussion Span
Last Post by jonniebl

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")

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.