HttpResponse Transmit File - stopping following code - c#

I have an asp.net button which calls this method.
protected void DownloadFile(object sender, EventArgs e)
{
Response.Clear();
string filePath = getFilePath();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=FvGReport.xlsx");
Response.TransmitFile(filePath);
Response.End();
newReportMessage.Visible = false;
}
But the newReportMessage.Visible component is never able to run. Through reading around I could see that Response.End() just terminates the thread and so that made sense. So I have tried what seems to work for a lot of other people.
protected void DownloadFile(object sender, EventArgs e)
{
Response.Clear();
string filePath = getFilePath();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=FvGReport.xlsx");
Response.TransmitFile(filePath);
Response.Flush();
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
newReportMessage.Visible = false;
}
But it still doesn't work? Does anyone know what the problem is so I can avoid this in the future, and what is the solution?

Related

Solution ASP.net call method from url to view pdf

I am trying to call a method to view a PDF
I am attempting to call the method from the URL eg. /Home.aspx/ViewPDF
The ViewPDF in the url is the method in the Home.aspx file.
I am new to ASP and this has stumped me, thanks if you can provide any help
EDIT 1:
I have an asp button with this in it's click method and it works:
protected void test12_Click(object sender, EventArgs e)
{
string FilePath = Server.MapPath("/Tasks/Content/54874/dummy.pdf");
WebClient User = new WebClient();
Byte[] FileBuffer = User.DownloadData(FilePath);
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
}
}
How would I be able to make the same thing happen from visiting /Home.aspx/ViewPDF
with /ViewPDF being a method inside the code behind of Home.aspx
I believe the method needs to be static to be able to view it from the url is there any alternative for defining the file path as Server.MapPath is not static.
I have made a test method in Home.aspx:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(object sender, EventArgs e)
{
return "test";
}
But when I visit /Home.aspx/test it just loads a version of the page with no images and slightly off css
Thanks for any help
Edit 2 / Solution:
After doing a bit of looking around on google you can easily implement MVC into web forms
https://www.davepaquette.com/archive/2013/12/30/so-you-inherited-an-asp-net-web-forms-application.aspx
From that I made a controller
public FileResult GetTaskAttatchment()
{
string ReportURL = Server.MapPath("/Tasks/Content/54874/dummy.pdf");
byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL);
return File(FileBytes, "application/pdf");
}
Which now works perfectly, Thanks again for all the help
//check your datatype for attachment shuld be varbinary...
protected void btnfinalupload_Click(object sender, EventArgs e)
{
string filename = "";
string filenameret = "";
using (DataSet ds = GetFormForDownload(id,finid))
{
if (ds.Tables[0].Rows.Count > 0)
{
filenameret = ds.Tables[0].Rows[0]["attachment"].ToString().Trim();
filename = ds.Tables[0].Rows[0]["filename"].ToString().Trim();
byte[] bytes;
string fileName, contentType;
bytes = (byte[])ds.Tables[0].Rows[0]["attachment"];
contentType = "application/pdf";
fileName = filename;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}

Download .dat file from server

I have been trying to write a code to download file from the server, the path is correct but the file isn't downloading when I click it.
The delete code works properly which looks like this:
protected void DeleteFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
File.Delete(filePath);
GenerateDownloadLinks();
}
However the download isn't starting the download (debugging runs through entire code):
protected void ButtonDownload_Click(object sender, EventArgs e)
{
string path = (sender as LinkButton).CommandArgument;
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
HttpResponse response = HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.AddHeader("content-disposition",
"attachment; filename=" + name);
response.ContentType = "text/plain";
response.TransmitFile(path);
response.Flush();
response.End();
}
The file I am downloading is a .dat file. I tried changing and adding the configurations but with no luck
Problem was update panel related, my datalist was inside an update panel

How to read a PDF,Word and Excel files from LinkButton click ? + Asp.Net + C#

How to read a PDF ,Word and Excel files from LinkButton click ? + Asp.Net+ C#.
This is my code :
protected void LinkButton155_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "application/vnd.msword";
Response.AppendHeader("content-disposition", "attachment; filename=" + "C:\\inetpub\\wwwroot\\suppression des doublons.docx");
Response.Flush();
Response.WriteFile("C:\\inetpub\\wwwroot\\suppression des doublons.docx");
}
For PDF Files :
protected void LinkButton154_Click(object sender, EventArgs e)
{
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=Acces_aux_marches.pdf");
Response.TransmitFile(Server.MapPath("~/App_Data/Accès aux marchés/Acces_aux_marches.pdf"));
Response.End();
}
For Excel Files:
protected void LinkButton153_Click1(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment; filename=" + "C:\\inetpub\\wwwroot\\decret.xlsx");
Response.Flush();
Response.WriteFile("C:\\inetpub\\wwwroot\\decret.xlsx");
}
protected void LinkButton155_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "application/vnd.msword";
Response.AppendHeader("content-disposition", "attachment; filename=" + "C:\\inetpub\\wwwroot\\decret.docx");
Response.Flush();
Response.WriteFile("C:\\inetpub\\wwwroot\\decret.docx");
}

How to close a web page from code behind after succesful download of a file through Response object in c#?

I have a very particular scenario where user can download a file from server by clicking on a button on the web page. I am achieving this through Response object. This is working fine.
But now I want to close the web page once the download completes. I have already tried the below code.
protected void btnDownloadFM_Click(object sender, EventArgs e)
{
bool isSucced = DownloadFile();
if (isSucced)
{
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}
}
The above code is not working. But if I comment out the file download code it is working fine(the web page close properly).
protected void btnDownloadFM_Click(object sender, EventArgs e)
{
//bool isSucced = DownloadFM();
bool isSucced = true;
if (isSucced)
{
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}
}
Below is the code block for downloading the file.
private bool DownloadFM()
{
try
{
//Get the file byte array from DB.
byte[] bytes = GetFileBytesFromDB();
string fileName = "DownloadedFile.txt";
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
string contentDisposition;
if (Request.Browser.Browser == "IE")
contentDisposition = "attachment; filename=" + Uri.EscapeDataString(templateName);
else
{
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(templateName);
}
Response.AddHeader("Content-Disposition", contentDisposition);
Response.AddHeader("Content-Length", bytes.Length.ToString());
Response.AddHeader("X-Download-Options", "noopen");
Response.ContentType = "application/octet-stream";
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
Response.Close();
return true;
}
catch (Exception ex)
{
//Log error message to DB
return false;
}
}
Am I doing anything wrong here?
Try registering window close before close (Not tested)
Just found similar solution here
closing a window after Response.End
....
....
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
Response.Flush();
Response.Close();
OR
Response.Clear();
Response.Write("<script>window.close();</script>");
Response.Flush();
Response.End();
after flushing file you have to return and no need to close window after flushing content it's close automatically
protected void btnDownloadFM_Click(object sender, EventArgs e)
{
DownloadFile();
Return;
}
try this hope it helps you

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