Merhaba arkadaşlar bu makalemizde bir text dosyası indirme
işlemi yapacağız. Bu metodla excel, word gibi dosyaları da indirebilirsiniz. İndirme
işlemi için Response metodunu kullanacağız. Response metodu ile ilgili gerekli
açıklamayı kod kısmında bulabilirsiniz.
Şekil 1
Şekil 2
Şekil 3
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace download_file
{
public partial class WebForm1 :
System.Web.UI.Page
{
protected void Page_Load(object sender,
EventArgs e)
{
Label1.Text = "Click
the button to download a file" + "<br>" +" (Bir
dosya indirmek icin butona tikla)";
}
protected void
btnDownload_Click(object sender, EventArgs e)
{
string filePath = "D:\\test.txt";
//string
filePath = "D:\\test.xlsx";
FileInfo file = new
FileInfo(filePath);
if (file.Exists)
{
// clear response reference
// cevap referansini temizle
Response.Clear();
// add header by specifying file name
// dosya adi belirtilerek baslik ekle
Response.AddHeader("Content-Disposition", "attachment;
filename=" + file.Name);
// add header for content length
// icerik uzunlugu icin baslik ekle
Response.AddHeader("Content-Length",
file.Length.ToString());
// specify
content type
// icerik turunu belirt
Response.ContentType = "text/plain";
// clearing flush
//flush i temizle
Response.Flush();
// transimiting file
// dosya aktarilmasi
Response.TransmitFile(file.FullName);
Response.End();
}
else Label1.Text =
"Requested
file is not available to download" + "<br>" + "
(Talep edilen dosya indirilemiyor)";
}
}
}
WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="download_file.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Font-Names="Arial" Font-Size="Large" Text="Label"></asp:Label>
<br />
<br />
<asp:Button ID="btnDownload" runat="server" Font-Names="Arial" Font-Size="Large" Height="36px" OnClick="btnDownload_Click" Text="Download" Width="147px" />
</div>
</form>
</body>
</html>
Bir
makalenin daha sonuna geldik. Bir sonraki makalede görüşmek üzere. Bahadır
ŞAHİN
0 comments:
Yorum Gönder