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

本文关键字:搜索 pdf 文件 WebForm 应用程序 | 更新日期: 2023-09-27 18:15:24

当我点击搜索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();
}

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

首先,您必须保存文件的全名以便稍后获取它。所以,你必须从:

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