File not downloading using response object - c#

So I have a controller method that creates an excel package and sends the response back to the user to save/download. The problem that I am having is that the response is not prompting the Open/Save dialog from appearing. Is there something I am missing?
[HttpPost]
public ActionResult Export()
{
var excel = do stuff to create open XML package
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + Convert.ToString(fileName).Replace(" ", "_") + ".xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.BinaryWrite(excel.GetAsByteArray());
Response.Flush();
Response.End();
}
return null

Related

excel cannot open the file because the file format or file extension is not valid c#

I am trying to download an excel file which for which I am giving the proper path. But after downloading it when I am trying to open I get error as
excel cannot open the file because the file format or file extension is not valid. Verify that file has been corrupted...
But If I open that file directly it gets open, I don't understand what is the issue in it. Below is my code
protected void MultipleSpanLinkIdDownLoadbtn_Click(object sender, EventArgs e)
{
try
{
string fileName = "multiSpanLinkeid.xlsx";
FileInfo file = new FileInfo(System.Configuration.ConfigurationManager.AppSettings["MultipleSpanLinkFolder"].ToString() + "/" + fileName);
if (file.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.AddHeader("Content-Type", "application/Excel");
Response.ContentType = "application/vnd.xls";
Response.AddHeader("Content-Length", file.Length.ToString());
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
catch (Exception)
{
ClientScript.RegisterStartupScript(this.GetType(), "Exception", "alert('Template downloaded.');", true);
}
}
Please suggest what is wrong in this
NOTE: The issue arises while downloading it from Chrome
Please try with this content type.
Response.ContentType = "application/vnd.ms-excel";
or
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Try this:
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

Shows warning message in exported xlsx file

My xlsx file is downloaded but when I open that xlsx file it shows warning as
'We found a problem with some content in'.
Can anyone tell me where I have to fix this? I am using an iFrame to download the file.
using (ClosedXML.Excel.XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Sheet1");
Response.Clear();
Response.Charset = "";
Response.Buffer = true;
Response.BinaryWrite(bytes);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + >Model.reportName + "_" + DateTime.Now.ToString("yyyyMMddHH:mm") + "." + extension);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}

TransmitFile is not working

I have a file, and it is full path (plus the file name) is in this variable:
fileTemporary
i want to download that file to the client.
i do this:
HttpContext.Current.Response.TransmitFile(fileTemporary);
but nothing happen, i mean when i click the button, this file executes, but nothing is being downloaded to the client. i don't see any file on the browser of the client.
what mistake did i do please?
If you use MVC you can:
[HttpGet]
public virtual ActionResult GetFile(string fileTemporary)
{
// ...preparing file path... init fileTemporary.
var bytes = System.IO.File.ReadAllBytes(fileTemporary);
var fileContent = new FileContentResult(bytes, "binary/octet-stream");
Response.AddHeader("Content-Disposition", "attachment; filename=\"YourFileName.txt\"");
return fileContent;
}
If you use ASP.NET or whatever you can use following (sorry, my old code, but you can understand approach):
var bytes = System.IO.File.ReadAllBytes(fileTemporary);
SendFileBytesToResponse(bytes, fileName);
public static bool SendFileBytesToResponse(byte[] bytes, string sFileName)
{
if (bytes!= null)
{
string downloadName = sFileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition",
"attachment; filename=" + downloadName + "; size=" + bytes.Length.ToString());
response.Flush();
response.BinaryWrite(bytes);
response.Flush();
response.End();
}
return true;
}
Without reingeneering your solution:
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "binary/octet-stream");
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName);
System.Web.HttpContext.Current.Response.TransmitFile(fileName);
If you would like browser to interpret you file right, you will need to specify header "Content-Type" more precise.
Please see list of content types

Word and Excel files not getting downloaded in my asp.net website

the below code works if I try to download a .txt/.msg/.pdf/.png/.jpg but it fails if I try to download exccel or word files. Can anybody please help
Response.ContentType = "APPLICATION/OCTET-STREAM";
//Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
fileUrl = Server.UrlDecode(fileUrl);
System.String disHeader = "attachment; filename=\"" + fileUrl + "\"";
Response.AppendHeader("Content-Disposition", disHeader);
// transfer the file byte-by-byte to the response object 
System.IO.FileInfo fileToDownload = new System.IO.FileInfo(fileUrl);
Response.Flush();
Response.WriteFile(fileToDownload.FullName);

Create Zip in c#

I am actually wondering why when I create a zip file, and I download it just after, I can't open it because it's broken ..
This is the code I am actually using .
string url = ((LinkButton)sender).Tag;
var downloadFileName = string.Format(((LinkButton)sender).ID + ".zip");
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C://inetpub//wwwroot//Files//Wireframes//" + url);
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("C://inetpub//wwwroot//Files//Wireframes//" + url, zip.Name);
zip.AddDirectory("C://inetpub//wwwroot//Files//Wireframes//" + url);
zip.Save(downloadFileName);
}
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
Also, I am adding directly all the directories with their files inside.
You are not sending the actual data.
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
Response.TransmitFile(downloadFileName);
Response.End();

Categories