I had problem with export data to .csv file. I use 2 methods.
Encoding csvEncoding = new UTF8SignatureEncoding();
byte[] csvFile = TestByte(CsvContentDelimiter.NewLine, CsvContentDelimiter.Semicolon, csvEncoding);
string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "text/csv";
Response.ContentEncoding = csvEncoding;
Response.AppendHeader("Content-Disposition", attachment);
Response.BinaryWrite(csvFile);
Response.Flush();
Response.End();
And
public byte[] TestByte(CsvContentDelimiter rowDelimiter, CsvContentDelimiter columnDelimiter, Encoding encoding)
{
StringBuilder sb = new StringBuilder();
sb.Append("product;");
return encoding.GetBytes(sb.ToString());
}
This code create .csv file, but file have bad Encoding and i see only some "hash"
Here is a fully working example using UTF8 formatting. It uses your own code so shows that it is your Encoding that is causing the issue:
namespace WebApplication1
{
using System;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void btnExport_Click(object sender, EventArgs e)
{
// Use UTF8 encoding
Encoding csvEncoding = Encoding.UTF8;
byte[] csvFile = TestByte(csvEncoding);
string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "text/csv";
Response.ContentEncoding = csvEncoding;
Response.AppendHeader("Content-Disposition", attachment);
Response.BinaryWrite(csvFile);
Response.Flush();
Response.End();
}
public byte[] TestByte(Encoding encoding)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Record1,Fred,Bloggs,26{0}", Environment.NewLine);
sb.AppendFormat("Record2,John,Smith,32{0}", Environment.NewLine);
return encoding.GetBytes(sb.ToString());
}
}
}
Related
I am trying to export the Gridview data to docx, but it doesnot work.
public static void SendToUserWord(GridView grid, string fileName, string type)
{
var response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", fileName));
response.Charset = "";
response.ContentType = type == "doc" ? "application/vnd.ms-word" : "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
response.ContentEncoding = Encoding.Default;
response.Write("<head><meta http-equiv=\"content-type\" content=\"text/html; charset="
+ Encoding.Default.WebName + "\"></head>");
response.Write(#"<style> td { mso-number-format:\#; } </style>");
using (var writer = new HtmlTextWriter(response.Output))
{
grid.RenderControl(writer);
}
response.End();
}
How do export to doxc?
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/
<%# WebHandler Language="C#" Class="dlde" %>
using System;
using System.Web;
public class dlde : IHttpHandler {
public void ProcessRequest (HttpContext context) {
var fileName = #"D:\Error.txt";
var r = context.Response;
r.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
r.ContentType = "text/plain";
r.WriteFile(context.Server.MapPath(fileName));
}
public bool IsReusable {
get {
return false;
}
}
}
I want to download the .txt file from the server system from the specified directory...i tried with this code,but i am getting error,invalid virtual path..How to get the file ,from the server system ..please help me...
try this by using "WebClient "
string remoteUri = "http://Yoursite.com/file.txt";
string fileName = #"D:\";
WebClient myWebClient = new WebClient();
myWebClient.DownloadFile(remoteUri, fileName);
Learning from MSDN for namespace
string fName = #"D:\Error.txt";
System.IO.FileStream fs = System.IO.File.Open(fName, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.AddHeader("Content-disposition", "attachment;
filename=" + HttpUtility.UrlEncode(fname, System.Text.Encoding.UTF8));
context.Response.ContentType = "text/plain";
context.Response.BinaryWrite(btFile);
string fName = #hdfRuta.Value; //Ruta donde se encuentra el archivo txt Ejm: c:\log\log21082018.txt
System.IO.FileStream fs = System.IO.File.Open(fName,
System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + hdfNombreArchivo.Value); //hdfNombreArchivo: Nombre del archivo .txt a generarse Ejm: Log_21_08_2018.txt
EnableViewState = false;
Response.ContentType = "text/plain";
Response.BinaryWrite(btFile);
Response.End();
protected void btnBajarLog_PreRender(object sender, EventArgs e)
{
Button btn = (Button)sender;
ScriptManager newScriptManager =
(ScriptManager)Page.FindControl("scmRegistroMasivoEvento");
newScriptManager.RegisterPostBackControl(btn);
}
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();
}
I am using webmethod to download a .zip file but file is not download. my code run well without error, code is below:
[WebMethod]
public static void DownloadExtension(string ExtensionPath)
{
string filepath = HttpContext.Current.Server.MapPath(ExtensionPath);
FileInfo file = new FileInfo(filepath);
if (file.Exists)
{
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.ContentType = ReturnExtension(file.Extension.ToLower());
HttpContext.Current.Response.TransmitFile(file.FullName);
HttpContext.Current.Response.End();
}
}
private static string ReturnExtension(string fileExtension)
{
switch (fileExtension)
{
case ".zip":
return "application/zip";
default:
return "application/octet-stream";
}
}
i am using VS2008 any solution thank you.
u can try this method..it worked fine for me...hope it helps you to..
protected void Page_Load(object sender, EventArgs e)
{
StartZip(Server.MapPath("directory name"), "filename");
}
protected void StartZip(string strPath, string strFileName)
{
MemoryStream ms = null;
Response.ContentType = "application/octet-stream";
strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');
Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip");
ms = new MemoryStream();
zos = new ZipOutputStream(ms);
strBaseDir = strPath + "\\";
addZipEntry(strBaseDir);
zos.Finish();
zos.Close();
Response.Clear();
Response.BinaryWrite(ms.ToArray());
Response.End();
}
protected void addZipEntry(string PathStr)
{
DirectoryInfo di = new DirectoryInfo(PathStr);
foreach (DirectoryInfo item in di.GetDirectories())
{
addZipEntry(item.FullName);
}
foreach (FileInfo item in di.GetFiles())
{
FileStream fs = File.OpenRead(item.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string strEntryName = item.FullName.Replace(strBaseDir, "");
ZipEntry entry = new ZipEntry(strEntryName);
zos.PutNextEntry(entry);
zos.Write(buffer, 0, buffer.Length);
fs.Close();
}
}
Try to download the file through a .ashx handler file.