如何通过搜索在WebForm应用程序中打开pdf文件?

时间:2015-09-30 01:55:55

标签: c# asp.net pdf

当我点击搜索PDF文件的列表框时,它没有打开。

代码如下。有什么想法吗?

protected void Button1_Click(object sender, EventArgs e)
{
  ListBox1.Items.Clear();
  string search = TextBox1.Text;
  if (TextBox1.Text != "") 
  {
    string[] pdffiles = Directory.GetFiles(@"\\192.168.5.10\fbar\REPORT\CLOTHO\H2\REPORT\", "*" + TextBox1.Text + "*.pdf", SearchOption.AllDirectories);
    foreach (string file in pdffiles)
    {
      // ListBox1.Items.Add(file);
      ListBox1.Items.Add(Path.GetFileName(file));
    }
  }
  else
  {
    Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
  }
}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
  string pdffiles = ListBox1.SelectedItem.ToString();

  string.Format("attachment; filename={0}", fileName));

  ProcessStartInfo infoOpenPdf = new ProcessStartInfo();
  infoOpenPdf.FileName = pdffiles;
  infoOpenPdf.Verb = "OPEN";
  // Process.Start(file);
  infoOpenPdf.CreateNoWindow = true;
  infoOpenPdf.WindowStyle = ProcessWindowStyle.Normal;

  Process openPdf = new Process();
  openPdf.StartInfo = infoOpenPdf;
  openPdf.Start();
}

1 个答案:

答案 0 :(得分:1)

首先,您必须保存文件的全名才能在以后获取。所以,你必须改变:

ListBox1.Items.Add(Path.GetFileName(file));

要:

ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));

然后,您应该将文件从服务器发送到客户端,如下所示:

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string fileName = ListBox1.SelectedValue;
    byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);

    System.Web.HttpContext context = System.Web.HttpContext.Current;
    context.Response.Clear();
    context.Response.ClearHeaders();
    context.Response.ClearContent();
    context.Response.AppendHeader("content-length", fileBytes.Length.ToString());
    context.Response.ContentType = "application/pdf";
    context.Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
    context.Response.BinaryWrite(fileBytes);
    context.ApplicationInstance.CompleteRequest();
}

注意:请勿忘记使用设置为ListBox的媒体资源AutoPostBack初始化您的true