Download from the tree node within a folder - c#

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

Related

Application freezes when I open a file dialog

I want it so that when the user clicks on the button and opens an image, the image gets copied to another location and the filepath of the copied image is saved inside 'Properties.Settings.Default.custombgfilepath'
Here is my code:
private void Button2_Click(object sender, EventArgs e)
{
//check for openfile dialog result
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
//initialize destination
string destination = #"C:\Launchicity\";
//Get filename
string filename = Path.GetFileName(openFileDialog1.FileName);
//get filepath
string filepath = destination + filename;
if (!File.Exists(filepath))
{
File.Copy(openFileDialog1.FileName, filepath);
Properties.Settings.Default.custombgfilepath = filepath;
Properties.Settings.Default.Save();
}
else
{
Properties.Settings.Default.custombgfilepath = filepath;
Properties.Settings.Default.Save();
}
}
}
Here is the Windows Form Designer auto genertaed code for openfiledialog1:
//
// openFileDialog1
//
this.openFileDialog1.Filter = "\"PNG (*.png)|*.png|JPG (*.jpg)|*.jpg\"";
this.openFileDialog1.Title = "Browse Image";
this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.OpenFileDialog1_FileOk);
When I click on the button however, the application freezes.
Can you please help me?
Thanks
More questions talk to me. Pls send me feedback ;) try this:
(Edited)
using system.IO
private void button1_Click(object sender, EventArgs e)
{
//check for openfile dialog result
this.openFileDialog1.Filter = "\"PNG (*.png)|*.png|JPG (*.jpg)|*.jpg\"";
this.openFileDialog1.Title = "Browse Image";
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
textBox1.Text = openFileDialog1.FileName;
//initialize destination
string destination = #"C:\Launchicity\";
//Get filename
string filename = Path.GetFileName(openFileDialog1.FileName);
//get filepath
string filepath = destination + filename;
if (!File.Exists(filepath))
{
File.Copy(openFileDialog1.FileName, filepath);
//Properties.Settings.Default.custombgfilepath = filepath; i dont have custombgfilepath
Properties.Settings.Default.Save();
}
else
{
//Properties.Settings.Default.custombgfilepath = filepath; i dont have custombgfilepath
Properties.Settings.Default.Save();
}
}

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.

Binding grid after generating pdf and creating download

I have a page with grid that generates PDF files using iTextSharp dll. The code is as following:
var document = new Document();
bool download = true;
if (download == true)
{
PdfWriter.GetInstance(document, Response.OutputStream);
BindGrid();
}
string fileName = "PDF" + DateTime.Now.Ticks + ".pdf";
try
{
document.Open();
// adding contents to the pdf file....
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
finally
{
document.Close();
BindGrid();
}
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Flush();
Response.End();
BindGrid();
}
I need to bind the grid once the download window pops up, or after user clicks to download it doesn't matters, I just need the grid to bind after the user generates the pdf file. I have tried binding the grid on numerous places as you can see, but none of them worked, the grid binds only after I refresh the page :(.
Is there any way I can do this ???
Response.End ends the page life cycle.
I suggest you to:
Generate the PDF file and save it on the server
Bind the grid
Flush the generated file
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindGrid(); // Bind the grid here
// After reloading the page you flush the file
if (Session["FILE"] != null)
FlushFile();
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Generate & Save PDF here
Session["FILE"] = fullFilePath; // The full path of the file you saved.
Response.Redirect(Request.RawUrl); // This reload the page
}
private void FlushFile()
{
string fullFilePath = Session["FILE"].ToString();
Session["FILE"] = null;
// Flush file here
}
Hope this helps.
Cheers

How to download PDF file from files on button click?

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

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