How to download PDF file from files on button click? - c#

I want to dowlnload a PDF file on a button click. I've try like that:
protected void lbtnDownload_Click(object sender, EventArgs e)
{
if (lbtnDownload.Text != string.Empty)
{
else if (lbtnDownload.Text.EndsWith(".pdf"))
{
Response.ContentType = "application/pdf";
}
string filePath = lbtnDownload.Text;
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(HttpContext.Current.Server.MapPath("~/") + "\\PDF\\" + filePath );
Response.End();
}
}
But nothing happens, I mean when I debug it there is no exception, but the file is not downloading.
Does anyone knows where my mistake is, and what I should do to download the PDF?

Try this
protected void btnUpload_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(txtName.Text)) return;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + txtName.Text);
string filePath = Server.MapPath(Path.Combine("~/SavedFolder/PDF", txtName.Text));
Response.TransmitFile(filePath);
Response.End();
}

Related

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.

aspx form textbox values to word.dot bookmark

I was wondering if anyone had a quick solution to have a button click to pass values from aspx web form to a word.dot. I have a button that opens my template but i would like it to pass textbox.text to book marks in the word template
e.g textbox1.text = bookmark.ID textbox2.text = bookmark.Fname
textbox3.text = bookmark.Lname textbox4.text = bookmark.Address ext...
protected void Button7_Click(object sender, EventArgs e)
{
string fPath = #"\\Server12\170912.dot";
FileInfo myDoc = new FileInfo(fPath);
Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("content-disposition", "attachment;filename=" + myDoc.Name);
Response.AddHeader("Content-Length", myDoc.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(myDoc.FullName);
Response.End();
}
Thank you in advance as always

asp.net listbox_index changed postback is firing on every button

I have a listbox that is populating on a buttonclick and then when the user selects or changes the index on the listbox it downloads a file related to it.
The problem I have is when they go to push a button to search a new record it downloads the file again but firing the code below again. How can I stop it from calling the postback on other buttons?
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string splitval = ListBox1.SelectedValue.ToString();
string[] newvar = splitval.Split(',');
GlobalVariables.attachcrq = newvar[0];
GlobalVariables.num = UInt32.Parse(newvar[1]);
string filename = ListBox1.SelectedItem.ToString();
GlobalVariables.ARSServer.GetEntryBLOB("CHG:WorkLog", GlobalVariables.attachcrq, GlobalVariables.num, Server.MapPath("~/TEMP/") + filename);
FileInfo file = new FileInfo(Server.MapPath("~/TEMP/" + filename));
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AppendHeader("Content-Length", file.Length.ToString());
Response.ContentType = ReturnExtension(file.Extension.ToLower());
Response.TransmitFile(file.FullName);
Response.Flush();
Response.End();
}
IsPostback property should be used over here.
Enclose your code in condition if(!Page.Ispostback)
Following can be the approach:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) {
if(!Page.IsPostback)
{
string splitval = ListBox1.SelectedValue.ToString();
string[] newvar = splitval.Split(',');
GlobalVariables.attachcrq = newvar[0];
GlobalVariables.num = UInt32.Parse(newvar[1]);
string filename = ListBox1.SelectedItem.ToString();
GlobalVariables.ARSServer.GetEntryBLOB("CHG:WorkLog", GlobalVariables.attachcrq, GlobalVariables.num, Server.MapPath("~/TEMP/") + filename);
FileInfo file = new FileInfo(Server.MapPath("~/TEMP/" + filename));
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AppendHeader("Content-Length", file.Length.ToString());
Response.ContentType = ReturnExtension(file.Extension.ToLower());
Response.TransmitFile(file.FullName);
Response.Flush();
Response.End();
}
}
MSDN Referance For IsPostBack:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
Usage With Example:
http://www.geekinterview.com/question_details/60291
Hope Its Helpful.

Download from the tree node within a folder

protected void Page_Load(object sender, EventArgs e)
{
field1.Text = (string)(Session["rolename"]); //from the page before. eg:IT Folder
field2.Text = (string)(Session["fullname"]);
if (Page.IsPostBack == false)
{
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo("C:\\Documents and Settings\\itdept\\Desktop\\Files\\"+ field1.Text);
TreeNode RootNode = OutputDirectory(RootDir, null);
MyTree.Nodes.Add(RootNode);
}
}
protected void click(object sender, EventArgs e) //onselectednodechanged from the treenode in aspx page
{
string file = ("C:\\Documents and Settings\\itdept\\Desktop\\Files\\" + field1.Text + "\\" + MyTree.SelectedValue);
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment;filename=" + file);
Response.ContentType = "text/xml";
Response.WriteFile(file); // here is the problem
Response.End();
}
**i can download files from the IT Folder, but in case there is a folder inside the IT Folder and i want to download something from that folder, i cannot download it.
does anyone have an idea how to make all things inside a folder even in a folder is downloadable?
thank you. :D

Dynamically added link button click event does not execute

I have dynamically added few link buttons inside a grid view with this code:
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string compositeFiles = e.Row.Cells[3].Text;
// split the string into individual files using delemeter "?"
string[] fileSet = compositeFiles.Split('?');
e.Row.Cells[3].Text = "";
foreach (string str in fileSet)
{
if (str != null)
{
// add a link button to the cell of the data grid.
LinkButton lb = new LinkButton();
lb.Text = "Download File";
lb.ID = str; // str is file URL
lb.Click += new EventHandler(lbStatus_click);
e.Row.Cells[3].Controls.Add(lb);
}
}
}
}
In my event handler, I have read the URL from the ID and downloading the file as octet stream.
private void lbStatus_click(object sender, EventArgs e)
{
string fileName = ((Control)sender).ID;
FileInfo file = new FileInfo(fileName);
if (fileName != string.Empty && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName.Substring(fileName.LastIndexOf("\\") + 1));
Response.AddHeader("content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
}
The link bottons appear in the webpage fine, but the problem is when I click on them, the page simply gets refreshed and nothing happens. The event handler code never gets executed.
Is this problem related to postback of the page? if yes then how can I solve it?
You need to suscribe to the command event of the grid view and add whatever information you need to the CommandArgs property.
EDIT: Added example
public void Page_Load(object sender, EventArgs e ){
gvTicketStatus.RowCommand += new EventHandler(RowCommand);
}
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string compositeFiles = e.Row.Cells[3].Text;
// split the string into individual files using delemeter "?"
string[] fileSet = compositeFiles.Split('?');
e.Row.Cells[3].Text = "";
foreach (string str in fileSet)
{
if (str != null)
{
// add a link button to the cell of the data grid.
LinkButton lb = new LinkButton();
lb.Text = "Download File";
lb.CommandName = "download"; //this is useful if you need to add more links with different commands.
lb.CommandArgument = str;// str is file URL
e.Row.Cells[3].Controls.Add(lb);
}
}
}
}
In my event handler, I have read the URL from the ID and downloading the file as octet stream.
private void RowCommand(object sender, GridViewCommandEventArgs e)
{
string fileName = e.CommandArgument;
FileInfo file = new FileInfo(fileName);
if (fileName != string.Empty && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName.Substring(fileName.LastIndexOf("\\") + 1));
Response.AddHeader("content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
}
For more information, please read http://msdn.microsoft.com/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.80).aspx
I've seen this behavior many times before when adding controls dynamically. Make sure that the code which binds your datagrid (which in turn executes your gvTicketStatus_RowDataBound event) runs after each and every page postback. This needs to occur in order for the linkbutton control to persist its click event after the postback.

Categories

Resources