文件已被其他进程使用

时间:2017-11-21 13:48:48

标签: c# email-attachments

我遇到以下代码 C#的问题,我必须通过电子邮件发送报告查看器生成的文件,但是当我发送电子邮件时,程序会生成一个异常,说明该文件已在使用中通过另一个过程。我该如何解决?我把代码和错误放在下面。

错误:

该进程无法访问C:/Temp/ordine.pdf,因为它已被其他进程使用了​​!

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);
}

2 个答案:

答案 0 :(得分:2)

您根本不需要使用文件。你已经在一个字节数组中有attachement内容,所以只需:

attachment = new System.Net.Mail.Attachment(new MemoryStream(bytes), "ordine.pdf" );

完全删除以下代码行:

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

string filepath = "C:/Temp/ordine.pdf";

using (FileStream fs = new FileStream(filepath, FileMode.Create))
{
    fs.WriteAsync(bytes, 0, bytes.Length);
    fs.Close();
}

File.Delete(@"C:/Temp/ordine.pdf");

答案 1 :(得分:-3)

我的许多Excel文件都发生了这种情况,但只要我将它们置于ReadOnly模式,它们就能正常工作。试试这个:

variational_recurrent