Search code examples
c#email-attachments

File is already in use by another process


I have a problem with the following code C#, I must email a file generated by a report viewer, however when I send the email the program generates an exception saying that the file is already in use by another process . How can I fix it? I put the code and the error below.

Error:

the process can not access C:/Temp/ordine.pdf because it is already in use by another process!

C# CODE:

try
{
    string subPath = "C:/Temp/";
    if (!Directory.Exists(subPath))
    {
        Directory.CreateDirectory(subPath);
    }

    string filepath = "C:/Temp/ordine.pdf";
    byte[] bytes = reportViewerOrdine.LocalReport.Render("PDF", null);
    using (FileStream fs = new FileStream(filepath, FileMode.Create))
    {
        fs.WriteAsync(bytes, 0, bytes.Length);
        fs.Close();
    }

    //Invio l'email                
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("mail.server.com");
    mail.From = new MailAddress(u.GetEmail());
    mail.To.Add(myemail);
    mail.Subject = "--";
    mail.Body = "--";
    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("C:/Temp/ordine.pdf");
    mail.Attachments.Add(attachment);
    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential(u.GetEmail(), u.GetPassword());
    SmtpServer.EnableSsl = false;
    SmtpServer.Send(mail);
    File.Delete(@"C:/Temp/ordine.pdf");
    MessageBox.Show("Email send");
}
catch (Exception ex)
{
    MessageBox.Show("Error: " + ex);
}

Solution

  • This has happened to me with many Excel files, but as soon as I put them in ReadOnly mode, they work. Try this:

    FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);