在asp.net中下载文件后清除控件

时间:2013-12-27 04:10:07

标签: c# asp.net pdf-generation itextsharp

我有一个网格控件和树视图。主要功能是根据树和网格中的选择下载表单。所以它工作正常,我想要做的是,在pdf下载后清除选择,不幸的是我的代码没有发生。我使用itextsharp生成pdf文件。我的代码如下

MemoryStream ms = new MemoryStream();
foreach (var file in filesToInclude)
{
    try
    {
        PdfReader ps = new PdfReader(file);
        PdfStamper pdf = new PdfStamper(ps, ms);//2
        pdf.Close();//4
        HttpContext.Current.Response.ClearContent();//5
        HttpContext.Current.Response.ClearHeaders();//6
        HttpContext.Current.Response.ContentType = "application/pdf";//7
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Session["Form_Name"]);//8
        HttpContext.Current.Response.BinaryWrite(ms.ToArray());//9
        ms.Flush();
        clearcontrols();
    }
    catch (Exception ex)
    { }
}

1 个答案:

答案 0 :(得分:1)

将代码放在finally块中,以便即使存在异常也始终将其清除。此外,有一个空的挡块不是一个好习惯。您正在抑制异常而不是处理异常。

MemoryStream ms = new MemoryStream();
foreach (var file in filesToInclude)
{
    try
    {
        PdfReader ps = new PdfReader(file);
        PdfStamper pdf = new PdfStamper(ps, ms);//2
        pdf.Close();//4
        HttpContext.Current.Response.ClearContent();//5
        HttpContext.Current.Response.ClearHeaders();//6
        HttpContext.Current.Response.ContentType = "application/pdf";//7
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Session["Form_Name"]);//8
        HttpContext.Current.Response.BinaryWrite(ms.ToArray());//9
        ms.Flush();
    }
    catch (Exception ex)
    {
        HandleException(); // Write code to handle exception 
    }
    finally
    {
         clearcontrols();
    }
}