Page.aspx
Page.aspx.cs
Le rôle de l'objet Response est de permettre de créer la réponse HTTP qui va être envoyée au navigateur, c'est-à-dire la page Web demandée par le client.
<asp:GridView ID="GridViewTest" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="Key" AccessibleHeaderText="Key" HeaderText="Key"/>
<asp:BoundField DataField="Value" AccessibleHeaderText="Value" HeaderText="Value" />
<asp:ButtonField AccessibleHeaderText="Test" HeaderText="Bouton" Text="Bouton" CommandName="DownloadFile" ButtonType="Button" />
</Columns>
</asp:GridView>
Page.aspx.cs
Le rôle de l'objet Response est de permettre de créer la réponse HTTP qui va être envoyée au navigateur, c'est-à-dire la page Web demandée par le client.
protected void Page_Load(object sender, EventArgs e)
{
List<string> names = new List<string>();
Dictionary<string,string> dico = new Dictionary<string,string>();
dico.Add("libelle","exemplelibelle");
GridViewTest.DataSource = dico;
GridViewTest.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DownloadFile")
{
Response.ClearHeaders();
Response.Clear();
Response.Expires = 0;
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment; filename=download.txt");
Response.ContentType = "text/plain";
Response.BinaryWrite(getImageByte("C:\\test\\file.txt"));
Response.End();
}
}
private byte[] getImageByte(String filename)
{
byte[] buffer = null;
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader binaryreader = new BinaryReader(fs);
long totalbytes = new FileInfo(filename).Length;
buffer = binaryreader.ReadBytes((Int32)totalbytes);
fs.Close();
fs.Dispose();
binaryreader.Close();
return buffer;
}
catch (Exception e)
{
log.Error("ERREUR : " + e.ToString());
}
return null;
}
{
List<string> names = new List<string>();
Dictionary<string,string> dico = new Dictionary<string,string>();
dico.Add("libelle","exemplelibelle");
GridViewTest.DataSource = dico;
GridViewTest.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DownloadFile")
{
Response.ClearHeaders();
Response.Clear();
Response.Expires = 0;
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment; filename=download.txt");
Response.ContentType = "text/plain";
Response.BinaryWrite(getImageByte("C:\\test\\file.txt"));
Response.End();
}
}
private byte[] getImageByte(String filename)
{
byte[] buffer = null;
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader binaryreader = new BinaryReader(fs);
long totalbytes = new FileInfo(filename).Length;
buffer = binaryreader.ReadBytes((Int32)totalbytes);
fs.Close();
fs.Dispose();
binaryreader.Close();
return buffer;
}
catch (Exception e)
{
log.Error("ERREUR : " + e.ToString());
}
return null;
}
No comments:
Post a Comment