Download File

Download File

using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class _Default : System.Web.UI.Page
{
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        DownloadFile("abc.txt", @"C:\"); //注意!!下載的檔案不能為0KB
    }

    protected void DownloadFile(string fileName, string filePath)
    {
        System.Net.WebClient net = new System.Net.WebClient();
        string link = filePath + fileName;

        Response.ClearHeaders();
        Response.Clear();
        Response.Expires = 0;
        Response.Buffer = true;
        Response.AddHeader("Accept-Language", "zh-tw");
        Response.AddHeader("Content-Disposition", "Attachment;FileName="
            + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
        Response.ContentType = "APPLICATION/octet-stream";
        Response.BinaryWrite(net.DownloadData(link));
        Response.End();
    }
}