c# - Return multiple files to download from asp.net -
who know how this? have loop , in loop list build up. want each list saved different file different filename (duh). using httpcontext.current.response this. single file works fine, however, cannot loop it. error receive upon second iteration "server cannot clear headers after http headers have been sent." code below. matters of course part commented // response user. comments highly appreciated!
cheerz, ronald
foreach (gridviewrow dr in gridview1.rows) { // find check box in row system.web.ui.webcontrols.checkbox cb = (system.web.ui.webcontrols.checkbox)dr.findcontrol("chkbx_selected"); // see if it's checked if (cb != null && cb.checked) { // cell datacontrolfieldcell cell = getcellbyname(dr, "guid"); string guid = new guid(cell.text); // record filtered on guid var result_json = call_webapi(guid); // result_json contains serialized list<string> list<string> result = jsonconvert.deserializeobject<list<string>>(result_json); // response user string filename = result[0] + ".txt"; httpcontext.current.response.clear(); httpcontext.current.response.clearheaders(); httpcontext.current.response.appendheader("content-disposition", string.format("attachment; filename={0}", filename)); httpcontext.current.response.contenttype = "application/octet-stream"; foreach (string line in result) { httpcontext.current.response.write(line + environment.newline); } httpcontext.current.response.flush(); } } httpcontext.current.response.end();
update: create zip archive in memory, create entry , fill writer. how create second entry in .zip?? code below not work, error "entries in create mode may written once, , 1 entry may held open @ time."
using (memorystream ziptoopen = new memorystream()) { using (ziparchive archive = new ziparchive(ziptoopen, ziparchivemode.create, true)) { ziparchiveentry readmeentry = archive.createentry("readme.txt"); using (streamwriter writer = new streamwriter(readmeentry.open())) { writer.writeline("information package."); writer.writeline("========================"); } list<string> result = new list<string>(); result.add("line1"); result.add("line2"); ziparchiveentry readmeentry2 = archive.createentry("readme2.txt"); using (streamwriter writer = new streamwriter(readmeentry.open())) { writer.write(result); } } using (var filestream = new filestream(@"c:\test.zip", filemode.create)) { ziptoopen.seek(0, seekorigin.begin); ziptoopen.copyto(filestream); } }
a single response can contain single "file". (technically http has no concept of "files", kind of why case. http has "headers" , "content". error tells you, once headers sent can't change them. because they've been sent client.)
you're either going have return files multiple requests/responses or compress them single file , return that.
(also, why use "application/octet-stream"
text file? use zipped file perhaps, text file should "text/plain"
or similar.)
Comments
Post a Comment