I have created PDF file using iTextsharp. while attaching to the email it gives this error :
IOException: The process cannot access the pdf file because it is being used by another process.
I tried dispose() and using statement to dispose the object but it didn't worked.
var font8 = FontFactory.GetFont(FontFactory.HELVETICA, 8);
var font9 = FontFactory.GetFont(FontFactory.HELVETICA, 9);
var boldfont8 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8);
var boldfont9 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 9);
var boldfont10 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10);
bool pageset = false;
Document myDocument = null;
var mypagesize = new iTextSharp.text.Rectangle(595f, 421f);
myDocument = new Document(mypagesize, 36, 36, 24, 24);
PdfWriter writer = PdfWriter.GetInstance(myDocument, new FileStream(filename1, FileMode.Create));
PdfPTable tablehead = new PdfPTable(1);
tablehead.TotalWidth = 530f;
tablehead.LockedWidth = true;
float[] widthshead = new float[] { 1f };
tablehead.SetWidths(widthshead);
tablehead.SpacingBefore = 2f;
myDocument.Open();
if (email == "email")
{
makeslip(myDocument, _payslip, _payroll.date2, notes);
myDocument.Close();
((IDisposable)myDocument).Dispose(); // tried this but didn't work
EmailController Sendmail = new EmailController(_contextAccessor, _env);
Sendmail.SendEmail(1, "saurabhnachankar@gmail.com", "", "", "TESTSubject", "TEST", filename1);
}
// Email Method
public IActionResult SendEmail(int id, string Email1, string Email2, string Email3, string EmailSubject, string EmailMessage, [Optional] string filename1)
{
mailMessage.Subject = EmailSubject;
mailMessage.Body = EmailMessage;
mailMessage.IsBodyHtml = true;
if (filename1 != null)
{
Attachment data = new Attachment(filename1); // At this point it is giving IOException
mailMessage.Attachments.Add(data);
client.Send(mailMessage);
data.Dispose();
}
}