Create Zip in c# - 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();

Related

Generate .csv UTF8 with ExcelPackage()

I am trying to generate a csv with UTF8 encoding with c#, using ExcelPackage (). Excel is identifying the file as .xlsx and not UTF8. My code:
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add("myName");
int y = 1;
foreach (IDictionary<string, string> elemento in losDatos)
{
ws.Cells["A" + y].Value = "+ Disposición de contacto";
ws.Cells["B" + y].Value = "Llamada detallada";
...
...
ws.Cells["AL" + y].Value = "1";
y++;
}
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
I have tried some changes, only in the Response piece, and now the csv recognizes me, but the characters are strangers:
Response.Clear();
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(Encoding.UTF8.GetPreamble());
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
Replace
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(Encoding.UTF8.GetPreamble());
with
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".xlsx");
and you are done.
If you want a CSV, use a different package but then do consider adding charset to the Content-Type header. If Open XML is not your thing, then OpenDocument Spreadsheet (.odt, LibreOffice) would be equally better than CSV.

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();
}

Why doesn't asp.net download work?

I am using this code to download a image i.e. I am storing Image name with extension in database and getting it here.
this code throws no error but doesn't download anything. why ?
try {
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
}
catch (Exception ex)
{
ResultLabel.ResultLabelAttributes(ex.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
}
finally
{
ResultPanel.Controls.Add(ResultLabel);
}
Update:
i tried this but doesn't work.
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath).CopyTo(m);
m.WriteTo(Response.OutputStream);
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
Create a Stream using following code
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath ).CopyTo(m);
m.WriteTo(Response.OutputStream);
You're on the right track using TransmitFile. Check this line:
Response.ContentType = ContentType;
It looks like you're setting the ContentType to the page's default.
Try specifying it explicitly:
Response.ContentType = "image/jpeg";

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);

Categories