Friday, January 14, 2011

Fast File Download - CSV in Asp.Net

protected void Button1_Click(object sender, EventArgs e)
{

string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection connecttion = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("select * from dbo.QUEUE");
command.CommandType = CommandType.Text;
command.Connection = connecttion;
command.Connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess);

////code for fast file download

Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + "fastfile" + ".CSV\"");


int i = 0;
while (reader.Read() && Response.IsClientConnected)
{
Response.Write(reader[0].ToString() + "\r\n");
if (i == 1000)
{
Response.Flush();
i = 0;
}
i++;

}

command.Connection.Close();
Response.Flush();
Response.End();
}