由于锁定文件C#

时间:2017-08-29 07:34:45

标签: c# pdf asp.net-web-api itext

我有一种情况,我从现有的pdf空白'证书'复制pdf,副本pdf包含一些添加到'蓝图'副本的个人信息。

将此邮件发送给用户后,我想再次将其删除,以免在服务器上保存副本。

无论我做什么,我都会收到错误消息

The process cannot access the file 'certificate#672712.pdf' because it is being used by another process.

很清楚消息的含义是什么,我想知道的是我应该如何改变证书创建部分的代码,以便在单词之后“释放”。

这是我使用的代码。

try
{
    string suffix =  (DateTime.Now.Day % 10 == 1 && DateTime.Now.Day != 11) ? "st of"
                    : (DateTime.Now.Day % 10 == 2 && DateTime.Now.Day != 12) ? "nd of"
                    : (DateTime.Now.Day % 10 == 3 && DateTime.Now.Day != 13) ? "rd of"
                    : "th of";
    string dateToday = string.Format("{0:dd}{1} {0:MMMM yyyy}", DateTime.Now, (suffix));
    Random generator = new Random();
    string referenceNumber = "#" + generator.Next(0, 1000000).ToString("D6");
    string bluePrint = HttpContext.Current.Server.MapPath("~/Certificates/blue_print.pdf");
    if (certificateNumber != "")
    {
        referenceNumber = certificateNumber;
    }
    string certificate = HttpContext.Current.Server.MapPath("~/Certificates/certificate_" + referenceNumber + ".pdf");
    PdfReader reader = new PdfReader(bluePrint); 
    using (PdfStamper stamper = new PdfStamper(reader, new FileStream(certificate, FileMode.Create)))
    {
        reader.SelectPages("1");
        var pageSize = reader.GetPageSize(1);


        PdfContentByte pbover = stamper.GetOverContent(1);
        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        pbover.SetColorFill(BaseColor.DARK_GRAY);
        Font font = new Font(bf);
        font.Size = 32;

        ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(UserName, font), 90, 305, 0);
    }
    reader.Close();              
    return referenceNumber;
}
catch (Exception exe)
{
    return exe.Message.ToString();
}

在我的控制器方法中,我按此顺序调用方法。

//certificate
    var reference = UtilityService.GenerateCertificate(String.Format("{0} {1}", firstName, lastName), "");
    //Mail the certificate
    string message = await MailService.MailTheCertificate(user.Email, "Well done", "Well done on completing the course", reference);

    //THE ERROR HAPPENS AS I AM TRYING TO DELETE THE CERTIFICATE
    FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath("~/Certificates/certificate_" + reference + ".pdf"));

    file.Delete();
    return Ok("success");

0 个答案:

没有答案