Skip to content

Instantly share code, notes, and snippets.

@KentaYamada
Last active August 29, 2015 14:05
Show Gist options
  • Save KentaYamada/36b2cd9fae5ece4ec6c3 to your computer and use it in GitHub Desktop.
Save KentaYamada/36b2cd9fae5ece4ec6c3 to your computer and use it in GitHub Desktop.
WebブラウザからCSVファイルをダウンロードするプログラム
//****************************************************
//Title:Web経由でCSVファイルをダウンロードするサンプル
//Author:Kenta Yamada
//Creation date:2014/08/09
//****************************************************
using System;
using System.IO;
using System.Text;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void btnDownLoad_Click(object sender, EventArgs e)
{
//ダウンロードファイルのファイル名を設定
this.Response.AddHeader("Content-Disposition", "attachment;filename=test.csv");
//ダウンロードデータとして設定
this.Response.ContentType = "application/octet-stream";
//エンコード設定
var enc = Encoding.GetEncoding("UTF-8");
//ダウンロード対象ファイルを読み込み
using (var sr = new StreamReader(@"\FilePath\test.csv", enc))
{
//ファイルデータ読み込み
string data = sr.ReadToEnd();
//バイナリ形式で出力
this.Response.BinaryWrite(enc.GetBytes(data));
this.Response.End();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment