venerdì 26 ottobre 2012

Eseguire un download da evento onclick di un button in c#

Il seguente codebehind può essere applicato all'evento onclick su di un pulsante button in ambiente .Net ed è utile per generare il download di un file.
L'utente, cliccando sul pulsante di una form, può eseguire il download del file example.txt

Esempio di pulsante su di una form.
<asp:button id="buttondownload" runat="server" text="Download" onclick="Download_Click"/>

Esempio codebehind:
 protected void Download_Click(object sender, EventArgs e)
 {
 string documentPath = "c:\\example.txt";
 try
 {
 if (!documentPath.Equals(""))
 {
  using (FileStream fs = File.OpenRead(documentPath))
  {
   int length = (int)fs.Length; byte[] buffer;
   using (BinaryReader br = new BinaryReader(fs)) { 
    buffer = br.ReadBytes(length); 
   } 
   Response.Clear();
   Response.Charset = "";
   Response.ClearContent();
   Response.ClearHeaders();
   Response.Buffer = true;
   Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Path.GetFileName(documentPath)));
   Response.ContentType = "text/plain"; //change for other format type: text/plain because it's a txt file
   Response.BinaryWrite(buffer);
   Response.Flush();
   Response.Close();
  }
 }
 }
 catch (Exception ex)
 {
 //code here
 }
}