I am looking for code to download a file to a clients pc, I would like to not store the physical file and worry about deleting it at a later stage. At the moment i create a physical file and then download it, the file name remains the same so it replaces the previous one. My concern is that multiple users might end up overwriting the file when both trying to download at the same time.
Here is some of my code:
using (var package = new ExcelPackage(existingFile))
{
// edit cells and add details into the excel file
//Here u save the file, i would like this to be a stream
using (FileStream aFile = new FileStream(MapPath("../../template/LeadsExport.xlsx"), FileMode.Create))
{
try
{
package.SaveAs(aFile);
aFile.Close();
}
catch (Exception ex)
{
}
}
// Here i download the file, i would like this to use a stream and not a physical file
FileInfo file = new FileInfo(MapPath("../../template/LeadsExport.xlsx"));
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
}
I would like to have the package saved into a file stream and not a physical file and then some way to download it.
You already have half the answer, in both code and in your question-text itself. Instead of writing the Excel package to disk, write it to the response stream.
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=LeadsExport.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(package.GetAsByteArray());
Response.End();