Reputation: 3626
I am currently developing an asp application with c# .net. I have to query a large(10GB) SQLite database and write the data as CSV format to HTTP response. I am doing this
/*query database, use string builder to create a csv*/
Response.ContentType = "text/plain";
Response.AddHeader("Content-Length", result.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=\"Data.csv\"");
Response.Write(result);
Response.Flush();
Which works file with small amount of data. But when the file size increases I get a OutOfMemoryException. I think using StringBuilder to create a string is causing the issue. I can not figure out any way to solve the issue. Can anyone please help me resolve this?
Upvotes: 2
Views: 4319
Reputation: 3626
I actually solved the problem. I did this
Response.Clear();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=\"Data.csv\"");
foreach(var item in dbItem)
{
/*create a string with database data*/
Response.write(string);
Response.Flush();
}
Response.End();
Upvotes: 2
Reputation: 11964
You need to read data by DataReader
and write it into Response.OutputStream
.
Something like this:
SqlDataReader dr;
//initialize datareader to your table
...
Response.Clear();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=\"Data.csv\"");
var writer = new StreamWriter(Response.OutputStream);
while (dr.Read())
{
writer.WriteLine(dr[1].ToString()+";"+dr[2].ToString()+";"+dr[3].ToString()+";");
Response.Flush();
}
Upvotes: 3