简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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