<%# 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);
}
Related
In my method in controller I use the following code to save pdf.
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlContent);
HtmlNode node = doc.GetElementbyId("DetailsToPDF");
HtmlToPdfConverter htmlToPdf = new HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment; filename=TEST.pdf");
Response.BinaryWrite(pdfBytes);
Response.Flush();
Response.End();
Everything has passed without any exceptions in debugger. However file is not saved. What am I doing wrong?
The recommended way to return a File in ASP.NET MVC is using the File() helper method:
public ActionResult Download()
{
// Starting with pdfBytes here...
// ...
var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = "TEST.pdf",
Inline = false
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(pdfBytes, "application/pdf");
}
string path = Server.MapPath("~/Content/files/newPDFFile.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + "PDFfile.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(buffer);
Response.End();
}
I use TransmitFile and WriteFile to write an Excel File, but anyone does not work correctly
my code is :
// Get the Physical Path of the file(test.doc)
string filepath = newFilePath;
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
HttpContext.Current.Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));
// Add the file size into the response header
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
HttpContext.Current.Response.TransmitFile(file.FullName);
}
FileStream sourceFile = new FileStream(file.FullName, FileMode.Open);
float FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Length", getContent.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
HttpContext.Current.Response.BinaryWrite(getContent);
I would simplify it to this instead:
public ActionResult ExcelDoc(string newFilePath)
{
string filepath = newFilePath;
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);
// Checking if file exists
if (file.Exists)
{
var fileBytes = System.IO.File.ReadAllBytes(filepath);
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));
return File(new MemoryStream(fileBytes), "application/vnd.ms-excel");
}
else
{
return Content("File does not exist");
}
}
I got a response which contains a PDF file
HttpWebResponse res = (HttpWebResponse)HttpWRequest.GetResponse();
Stream pdf = res.GetResponseStream();
I want to show this PDF on web browser without save it in a file. How could I do that?
I'm using the following code and works fine.
public static void SendDataByteFileToClient(HttpContext context, byte[] data, string fileName, string contentType, bool clearHeaders = true)
{
if (clearHeaders)
{
context.Response.Clear();
context.Response.ClearHeaders();
}
context.Response.BufferOutput = true;
context.Response.ContentType = contentType;
context.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
context.Response.AddHeader("Content-Length", data.Length.ToString());
if (BrowserHelper.IsOfType(BrowserTypeEnum.IE) && BrowserHelper.Version < 9)
{
context.Response.Cache.SetCacheability(HttpCacheability.Private);
context.Response.Cache.SetMaxAge(TimeSpan.FromMilliseconds(1));
}
else
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);//IE set to not cache
context.Response.Cache.SetNoStore();//Firefox/Chrome not to cache
context.Response.Cache.SetExpires(DateTime.UtcNow); //for safe measure expire it immediately
}
if (data.Length > 0)
{
context.Response.BinaryWrite(data);
}
context.Response.End();
}
HttpWebResponse res = (HttpWebResponse)HttpWRequest.GetResponse();
Stream pdfdata = res.GetResponseStream();
string path = pdfdata.ToString();
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
Response.End();
}
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());
}
}
}
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.