asp.net - download files in specific folder - asp.net

i'm trying download files that is located in specific folder. I'm using this code, but it gives me an error in Reponse.End(); -> Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack
if (m.Path.EndsWith(".txt"))
{
Response.ContentType = "application/txt";
}
else if (m.Path.EndsWith(".pdf"))
{
Response.ContentType = "application/pdf";
}
else if (m.Path.EndsWith(".docx"))
{
Response.ContentType = "application/docx";
}
else
{
Response.ContentType = "image/jpg";
}
string nameFile = m.Path;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + nameFile);
Response.TransmitFile(Server.MapPath(ConfigurationManager.AppSettings["IMAGESPATH"]) + nameFile);
Response.End();
I also tried Response.Write, but it gives me the same error.

Response.End will throw ThreadAbortException and it's there only for compatibility with old ASP and you should use HttpApplication.CompleteRequest
here is the example :
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Content-Disposition", "attachment;filename=pic.jpg");
context.Response.ContentType = "image/jpg";
context.Response.TransmitFile(context.Server.MapPath("/App_Data/pic.jpg"));
context.ApplicationInstance.CompleteRequest();
}
public bool IsReusable
{
get
{
return false;
}
}
}

Related

asp.net generic handler not sending images for the first time

I created a generic handler (.ashx) in ASP.Net to load images from database & send it to browser.
I am using a colorbox to display this in a separate page which only has an image control & calls this handler via ImageUrl property.
For the first time, Image is not being shown in the color box. For the subsequent requests, Image is getting shown.
I tried debugging to find that for the subsequent requests browser is not using a round trip but showing from cache.
How do I make it show the first time as well ?
public class DocumentViewer : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string querystring = context.Request.QueryString.ToString();
try
{
if (querystring != null && querystring.Trim().Length == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
string DocCode = querystring;
DocumentInfoBL bl = new DocumentInfoBL();
DataTable dt = bl.GetDocumentInfo(DocCode);
if (dt.Rows.Count == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.MinValue);
// context.Response.ContentType = "application/octet-stream";
context.Response.ContentType = MimeMapping.GetMimeMapping(System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.AddHeader("content-disposition", "inline; filename=" + System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.BinaryWrite((Byte[])dt.Rows[0]["DocumentFile"]);
context.Response.Buffer = false;
context.Response.Flush();
}
catch (Exception ex)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Code that works.It is either charset or Buffer.
public void ProcessRequest(HttpContext context)
{
string querystring = context.Request.QueryString.ToString();
try
{
if (querystring != null && querystring.Trim().Length == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
string DocCode = querystring;
DocumentInfoBL bl = new DocumentInfoBL();
DataTable dt = bl.GetDocumentInfo(DocCode);
if (dt.Rows.Count == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.MinValue);
context.Response.ContentType = MimeMapping.GetMimeMapping(System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.AddHeader("content-disposition", "inline; filename=" + System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.BinaryWrite((Byte[])dt.Rows[0]["DocumentFile"]);
context.Response.Flush();
}
catch (Exception ex)
{
//Manage here
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.End();
}

I can't open .pdf, .doc etc. file from other servers via SFTP using rebex

I have Two different servers as like below.
1. WebServer - Where is my application is locate
2. FileServer - where is my all uploaded files are locate in perticular location / Folder
Now in my web application I have created one page which display all uploaded files from FileServer (which i have uploaded).
But the issue is, when I try to open/read that file then I am not able. I have all rights of SFTP. and I am getting below issue in Try-catch block.
"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."
I have used REBEX for upload and download files.
Note : I can able to open simple text file (.txt) but not other formated files like (.PDF, .docx, .jpg etc.)
My file read code is like below.
protected void LinkButton1_Click(object sender, EventArgs e)
{
try
{
LinkButton lbtn = (LinkButton)sender;
using (Sftp _sftp = new Sftp())
{
_sftp.Connect(serverNm, 22);
_sftp.Login(username, password);
_sftp.ChangeDirectory(currentDirectory);
Stream stream = _sftp.GetStream(lbtn.ToolTip.ToString(), FileMode.Open, FileAccess.Read);
StreamReader sourceStream = new StreamReader(stream);
Byte[] buffer = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
Response.Buffer = true;
if (lbtn.ToolTip.IndexOf(".pdf") > 0)
{
Response.ContentType = "application/pdf";
}
else if (lbtn.ToolTip.IndexOf(".txt") > 0)
{
Response.ContentType = "text/plain";
}
else if (lbtn.ToolTip.IndexOf(".xls") > 0)
{
Response.ContentType = "application/ms-excel";
}
else if (lbtn.ToolTip.IndexOf(".doc") > 0)
{
Response.ContentType = "application/msword";
}
else if (lbtn.ToolTip.IndexOf(".jpeg") > 0)// || lbtn.ToolTip.IndexOf(".jpg") > 0)
{
Response.ContentType = "image/jpeg";
}
else if (lbtn.ToolTip.IndexOf(".jpg") > 0)
{
Response.ContentType = "image/jpg";
}
else if (lbtn.ToolTip.IndexOf(".bmp") > 0)
{
Response.ContentType = "image/png";
}
Response.AddHeader("Content-Length", "attachment;filename=" + buffer.Length.ToString());
Response.BinaryWrite(buffer);
Response.End();
}
}
catch (Exception ex)
{
}
}
So any one can help to fixe this issue.
I am using latest Mozila browser.
Thank you.
Would it be possible to post the complete stack trace of the exception here? You can get the stack trace by modifying the catch block like this:
try
{
//... your code
}
catch (Exception ex)
{
Response.ContentType = "text/plain";
Response.Write(ex.ToString());
Response.End();
}

Download all types of files from server using ASP.NET

I have a file in server .
I want download this file .
I use this code
try
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
if (File.Exists(Server.MapPath("~/Upload/" + file)))
{
Response.AddHeader("Content-Disposition", "attachment; filename=" + file);
Response.ContentType = "application/octet-stream";
Response.WriteFile(("~/Upload/" + file));
Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
else
{
if (Request.UrlReferrer != null)
{
Type csType = GetType();
string jsScript = "alert('File Not Found');";
ScriptManager.RegisterClientScriptBlock(Page, csType, "popup", jsScript, true);
}
}
}
catch (Exception ex)
{
string errorMsg = ex.Message;
ScriptManager.RegisterClientScriptBlock(Page, GetType(), "popup", errorMsg, true);
}
But when i use this, I get error
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
in code
Response.End();
How to download all types of files?
Is this Web Forms, MVC, or a custom IHttpHandler?
In any event, you don't need to call Response.End() or HttpContext.Current.ApplicationInstance.CompleteRequest(), just return from your function and ensure nothing else is written to the response.
Have you tried :
Response.TransmitFile(Server.MapPath("~/Upload/" + file));
instead of :
Response.WriteFile(("~/Upload/" + file));
You should also remove the BufferOutput (bad idea with Response.End() without Response.Flush())

Download PDF Document on Save as dialog

I am using following code for downloading PDF document in save as mode but there is a problem in IE,
anyone can resolve this prohlem?
private void DownloadFile(string fname, bool forceDownload)
{
string path = MapPath(fname);
string name = Path.GetFileName(fname);
string ext = Path.GetExtension(fname);
string type = "";
Response.ClearHeaders();
Response.ClearContent();
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".pdf":
type = "application/pdf";
break;
case ".doc":
case ".docx":
case ".rtf":
type = "Application/msword";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition", "attachment; filename=" + name);
}
if (type != "")
{
Response.ContentType = type;
Response.WriteFile(path);
Response.End();
}
}
thanks
Asim Hashmi
Maybe because you're using SSL?
check this: http://support.microsoft.com/kb/316431

Problem downloading a 25MB file - the 8MB file downloads without problem (ASP.NET)

I have two files at the same location but the big one, when is about to finish download, gives an error (both in IE and Firefox).
I use the following code:
public static void DownloadZipFile (string filename, bool notifyMe)
{
HttpContext context = HttpContext.Current;
HttpServerUtility server = context.Server;
bool ok = false;
try
{
string file = string.Format ("~/contents/licensing/members/downloads/{0}", filename);
string server_file = server.MapPath (file);
HttpResponse response = context.Response;
//response.BufferOutput = false;
response.ContentType = "application/zip";
string value = string.Format ("attachment; filename={0}", filename);
response.AppendHeader ("Content-Disposition", value);
FileInfo f = new FileInfo (server_file);
long size = f.Length;
response.TransmitFile (server_file, 0, size);
response.Flush ();
ok = true;
response.End ();
}
catch (Exception ex)
{
Utilities.Log (ex);
}
finally
{
if (ok && notifyMe)
NotifyDownload (filename);
}
}
Any ideas?
Response.End() calls Response.Flush(). Try removing the Flush call.
The solution to this problem is to add the line:
response.AddHeader("Content-Length",size.ToString());
before the call to TransmitFile ().
The credits go to Jim Schubert (see his comment above).

Resources