创建 pdf.The 进程时出错,无法访问正在被另一个进程使用的 file.because

giving error while creating pdf.The process cannot access the file.because it is being used by another process

我正在将网页 div 导出为 pdf 并将该邮件发送到 pdf。第一次创建 pdf 并发送邮件 properly.but 下次它给出错误提示。此行的另一个进程正在使用文件

 PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(strPath, FileMode.Create));

我的aspx.cs代码是-

System.IO.StringWriter stringWrite = new System.IO.StringWriter();


                System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
                design.RenderControl(htmlWrite);
                string myText = stringWrite.ToString().Replace("&", "&");
                StringReader sr = new StringReader(myText.ToString());
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);

                string strPath = Request.PhysicalApplicationPath + "\Temp\WeeklyReport of " + Projname + ".pdf";
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(strPath, FileMode.Create));
                pdfDoc.Open();
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);

                pdfDoc.Close();
                pdfDoc.Dispose();

                LblNoteMsg.Text = strPath;
                DateTime input = DateTime.Now;
                int delta = DayOfWeek.Monday - input.DayOfWeek;
                DateTime dats = DateTime.Now.AddDays(delta);
                //this week
                DateTime monday = input.AddDays(delta);
                string MonDate = monday.ToShortDateString();
                DateTime sat = monday.AddDays(5);
                string SatDate = sat.ToShortDateString();
                StreamReader r = new StreamReader(Server.MapPath("~/WeeklyMail.txt"));
                string body = r.ReadToEnd();
                MailMessage Msg = new MailMessage();
                string MailId = txtMailId.Text;
                foreach (string ss in MailId.Split(",".ToCharArray()))
                {
                    if (string.IsNullOrEmpty(ss) == false)
                    {
                        Msg.To.Add(new MailAddress(ss));
                    }
                }


                Msg.Subject = "Weekly status Report";
                Msg.Body = body;
                Msg.IsBodyHtml = true;
                Msg.Attachments.Add(new Attachment(strPath));

                SmtpClient MailServer = new SmtpClient();
                try
                {

                    MailServer.Send(Msg);

在下面的代码中,您可以为文件名添加一些时间戳,以便创建不同的文件。

string strPath = Request.PhysicalApplicationPath + "\Temp\WeeklyReport of " + Projname + ".pdf";

string strPath = Request.PhysicalApplicationPath + "\Temp\WeeklyReport of " + Projname + DateTime.Now.ToString("dd-MM-yyyy_HH:mm:ss") +".pdf";

我通过添加日期和时间更改了文件名。

string strPath = Request.PhysicalApplicationPath + "\Temp\WeeklyReport of " + Projname + DateTime.Now.ToString(" dd-MM-yyyy_HH-mm-ss") + ".pdf";

发送邮件后

Msg.Attachments.Dispose();