简体   繁体   English

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

[英]How to open a pdf file in a WebForm application by search?

When I click on the listbox which search a PDF file, it's not opening.当我单击搜索 PDF 文件的列表框时,它没有打开。

The code is below.代码如下。 Any thoughts?有什么想法吗?

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

First, you must save the file's full name to get it later.首先,您必须保存文件的全名以便以后获取。 So, you must change from:所以,你必须从:

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

To:到:

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

Then, you should send the file from the server to the client, like this:然后,您应该将文件从服务器发送到客户端,如下所示:

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

Note: don't forget to initialize your ListBox with the property AutoPostBack setted to true .注意:不要忘记将属性AutoPostBack设置为true来初始化ListBox

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM