How to export csv as a zip file in c# - c#

I am to create a CSV and write information to it and then download it.Now I have to download it as a zip format.
public void WriteToCSV(List<DeviceModel> DeviceList)
{
string attachment = "attachment; filename=DeviceModel.csv";
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "text/csv";
Response.AddHeader("Pragma", "public");
WriteColumnName();
foreach (DeviceModel Device in DeviceList)
{
WriteDeviceInfo(Device);
}
Response.End();
}

You can use a library for that :
http://dotnetzip.codeplex.com/

Related

how to create zip and stock it in a link MVC or provide zip to user and redirect

I am able to create a zip with no problem, the only thing I cannot do, stock the zip file in a link so that when the user clicks on the link it will download the file
Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=Photo.zip");
using (ZipFile zip = new ZipFile())
{
foreach (var pictures in pictureList)
{
zip.AddFile(Server.MapPath("~\\Content\\pictures\\upload\\" + pictures.name),"images");
}
zip.Save(Response.OutputStream);
}
Response.End();
Code below works for the file downloading.
public void DownloadFile(string fileName)
{
FileInfo file = new FileInfo(#"D:\DOCS\"+fileName);
Context.Response.Clear();
Context.Response.ClearHeaders();
Context.Response.ClearContent();
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Context.Response.AddHeader("Content-Length", file.Length.ToString());
Context.Response.ContentType = "application/zip";
Context.Response.Flush();
Context.Response.TransmitFile(file.FullName);
Context.Response.End();
}
However, Calling Response.Redirect after Response.End() will not going to work. If you really want to redirect the page you might have to think of an alternative way.

Creating PDF using C#

When I try to convert binary file to PDF the pdf has damaged.
byte[] stream = presenter.getItemTable();
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader ("Content-Disposition", "attachment; filename=PressRelease.pdf");
Response.BinaryWrite(stream);//Entities.EDRSearchResult.ByteStream);
Response.Flush();
Response.End();
However when I convert same binary to Excel it is working fine and can open without any error.
byte[] stream = presenter.getItemTable();
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/vnd.openxmlformats - officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition","attachment;filename=DataTable.xls");
Response.BinaryWrite(stream);
Response.Flush();
Response.End();
Please help me.
when you try to convert binary file to PDF in this case you write
Response.AddHeader ("Content-Disposition", "attachment; filename=PressRelease.pdf");
Try
Response.AddHeader ("content-disposition", "attachment; filename=PressRelease.pdf");

How to download Server files into client system using c#

string filePath1 = (sender as LinkButton).CommandArgument;
string filepath = ("D:\\RetailAgreement\\" + filePath1);
FileInfo myfile = new FileInfo(filepath);
if (filePath1 != "")
{
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);
Response.AddHeader("Content-Length", myfile.Length.ToString());
Response.ContentType = ReturnExtension(myfile.Extension.ToLower());
Response.TransmitFile(myfile.FullName);
Response.End();
}
I tried like this but it is not working ,
I don't know where i went wrong. I am using C#3.0
File.Copy("D:\\RetailAgreement\\",Server.Mapth("YourAplicationPath\\MyFiles"), true);
//Copy Files to Your Application Path
string path = Server.MapPath("~\MyFiles" + filePath1");
System.IO.FileInfo file = new System.IO.FileInfo(path);
string Outgoingfile = "myfile.xlsx";
if (file.Exists)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
else
{
Response.Write("This file does not exist.");
}
use this code.
string path = Server.MapPath("~/DownloadedExcelFilesOp4/myfile.xlsx");
System.IO.FileInfo file = new System.IO.FileInfo(path);
string Outgoingfile = "myfile.xlsx";
if (file.Exists)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
else
{
Response.Write("This file does not exist.");
}

Downloaded excel file not opening

I am trying to download excel file to the location in local system but on opening the file, i am getting error:
The file format or extension does not match.
Although the file at backend is of same extension but i am getting the error
PFB the code:
string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename="+downloadedFileName);
downloadedFileName= "Myfile.xlsx"
It will save as details.xls
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Details.xls"));
Response.ContentType = "application/ms-excel";
You have this error because you're not using Response.TransmitFile(). Your code should be:
string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename="+downloadedFileName);
Response.TransmitFile(FilePath); // full path here

ASP.NET file download from server

After a user clicks a button, I want a file to be downloaded. I've tried the following which seems to work, but not without throwing an exception (ThreadAbort) which is not acceptable.
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
response.TransmitFile(Server.MapPath("FileDownload.csv"));
response.Flush();
response.End();
You can use an HTTP Handler (.ashx) to download a file, like this:
DownloadFile.ashx:
public class DownloadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName + ";");
response.TransmitFile(Server.MapPath("FileDownload.csv"));
response.Flush();
response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Then you can call the HTTP Handler from the button click event handler, like this:
Markup:
<asp:Button ID="btnDownload" runat="server" Text="Download File"
OnClick="btnDownload_Click"/>
Code-Behind:
protected void btnDownload_Click(object sender, EventArgs e)
{
Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}
Passing a parameter to the HTTP Handler:
You can simply append a query string variable to the Response.Redirect(), like this:
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
Then in the actual handler code you can use the Request object in the HttpContext to grab the query string variable value, like this:
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];
// Use the yourVariableValue here
Note - it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...
Try this set of code to download a CSV file from the server.
byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
Making changes as below and redeploying on server content type as
Response.ContentType = "application/octet-stream";
This worked for me.
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
Further to Karl Anderson solution, you could put your parameters into session information and then clear them after response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));.
See MSDN page HttpSessionState.Add Method (String, Object) for more information on sessions.
protected void DescargarArchivo(string strRuta, string strFile)
{
FileInfo ObjArchivo = new System.IO.FileInfo(strRuta);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile);
Response.AddHeader("Content-Length", ObjArchivo.Length.ToString());
Response.ContentType = "application/pdf";
Response.WriteFile(ObjArchivo.FullName);
Response.End();
}
Simple solution for downloading a file from the server:
protected void btnDownload_Click(object sender, EventArgs e)
{
string FileName = "Durgesh.jpg"; // It's a file name displayed on downloaded file on client side.
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "image/jpeg";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(Server.MapPath("~/File/001.jpg"));
response.Flush();
response.End();
}

Categories

Resources