创建pdf时出错。进程无法访问该文件。因为它正被另一个进程使用

时间:2015-06-08 05:22:14

标签: c# asp.net pdf itextsharp

我将网页div导出为pdf并将该邮件发送到pdf。第一次创建pdf并正确发送邮件。但下次给出错误说。文件是由此行的另一个进程使用的

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

3 个答案:

答案 0 :(得分:2)

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

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";

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

发送电子邮件后

Msg.Attachments.Dispose();