System.Net.Mail - Error Opening the file. The file is write-protected or in use

I’ve built a class to loop through customers, pass a customer’s order to an AX report, save that report to PDF, and mail that report to the customer.

It works except for it seems that when I attach the pdf to email, AX keeps the file open so I can’t delete it or override it. Here’s my mail code. How can I release the file from AX?

Error is "Error opening the file “file here”. The file is write-protected or in use.

System.Net.Mail.MailMessage mailMessage;
System.Net.Mail.Attachment attachment;
System.Net.Mail.AttachmentCollection attachmentCollection;
System.Net.Mail.SmtpClient smtpClient;
System.Net.Mail.MailAddress mailAddressFrom;
System.Net.Mail.MailAddress mailAddressTo;
str Body;
str Subject;
str SMTPServer;
str FileName;
FileIOPermission perm;


mailAddressFrom = new System.Net.Mail.MailAddress("","");
mailAddressTo = new System.Net.Mail.MailAddress("","");
Body = “Test of some orders automatically emailed.”;
Subject = “Test Backorder send Batch AX”;
SMTPServer = SysEmailParameters::find(false).SMTPRelayServerName;

mailMessage = new System.Net.Mail.MailMessage(mailAddressFrom, mailAddressTo);
attachmentCollection = mailMessage.get_Attachments();

FileName = _fileName;

perm = new FileIOPermission(FileName,‘r’);

attachment = new System.Net.Mail.Attachment(FileName);
smtpClient = new System.Net.Mail.SmtpClient(SMTPServer);

// recommend that you still call revertAssert after invoking the protected API to limit the scope of the assert.

Sorry to bump, but any ideas here?


Also, it looks like you’re using a chopped up version of this…look how I handle the temp file:

Alex, perfect, thanks.