Download a string as a file in ASP.NET - asp.net

The following method, based on code in this question, shows a file download dialog box in the browser, but then the download never starts (it stays at 0%):
protected void lnkExport_Click(object sender, EventArgs e) {
var bytes = Encoding.ASCII.GetBytes(SelectRecords()); //Data to be downloaded
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=\"test.xls\"");
using (var stream = new MemoryStream(bytes)) {
Response.AddHeader("Content-Length", stream.Length.ToString());
stream.WriteTo(Response.OutputStream);
}
}
Any idea what's up?

Your code worked fine for me but you may want to try adding this as the last line of your click handler:
Response.End();

Related

How to download pdf file from database using asp gridview link button

I have stored binary data into a db.
When I'm fetching and trying to download same pdf file I'm unable to do it.
Below is my code snippet:
protected void grdDownload_Command(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
int index = Convert.ToInt32(e.CommandArgument);
DataTable dtFilterData = `enter code here`GetPDFFile("D", Convert.ToString(index));
Response.Clear();
Response.Buffer = true;
Response.ContentType = dtFilterData.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dtFilterData.Rows[0]["Name_File"].ToString()); // to open file prompt Box open or Save file
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dtFilterData.Rows[0]["FileData"]);
Response.End();
}
}
Finally i have resolved this issue. We need to add update panel for link button inside the Item template.
Adding Postback Trigger has resolved this issue.

How to let user select the location for downloading a file in asp.net?? To be precise a open file dialog equivalent in asp(Not fileUpload)

I am downloading a pdf file in my project. I want to let the user decide where to download the File. Quick help is helpful.
Thanks
try this:
It will display a dialog box in the browser and the user will select on where to save the file
protected void DownloadFile_Click(object sender, EventArgs e)
{
String Filepath;
System.IO.FileInfo file = new System.IO.FileInfo(Filepath); // full file path on disk
Response.ClearContent(); // Clear previous content
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
Response.TransmitFile(file.FullName);
Response.End();
}
You haven't specified how your application is serving this PDF file, but assuming that you have some WebForm which is streaming it to the Response, you should set the Content-Disposition header as attachment in order to force the Save As dialog in the browser.
For example:
protected void Download(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=example.pdf");
Response.WriteFile(#"c:\work\example.pdf");
}

How to flush xml file in asp.net?

I want to return a xml file to a client, and THEN perform my logic.
I try to use Response.Flush(), but it doesn't work correctly for me.
My code:
protected void Page_Load(object sender, EventArgs e)
{
string arg1= this.Request["arg1"];
string arg2= this.Request["arg2"];
string arg3= this.Request["arg3"];
var doc = new XmlDocument();
XmlNode responseNode = doc.CreateElement("response");
doc.AppendChild(responseNode);
var messageNode = responseNode.AppendChild(doc.CreateElement("message"));
messageNode.InnerText = "Your request is being processed";
Response.Clear();
Response.ContentType = "text/xml";
Response.ContentEncoding = System.Text.Encoding.UTF8;
doc.Save(Response.Output);
Response.Flush(); // I want to display xml in this moment but it doesn't work
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
Response.End();
}
Response.End();
Generally, it is a bad idea to be using Response.End() in your code.
From the source: This method is provided only for compatibility with ASP—that is, for compatibility with COM-based Web-programming technology that preceded ASP.NET. If you want to jump ahead to the EndRequest event and send a response to the client, it is usually preferable to call CompleteRequest instead.
Given this info, instead of this:
Response.Flush(); // I want to display xml in this moment but it doesn't work
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
Response.End();
do this:
Response.Flush(); // I want to display xml in this moment but it doesn't work
Response.CompleteRequest();
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
// here you might want to make sure that no other page handlers are executed

how to create a hyperlink for file download in asp.net?

I have some files stored on my machine. When a user wants to generate a link the page should generate a hyperlink. This hyperlink can be used by any other user so as to download the file
Have a LinkButton and for the click event do the following
your aspx file will have the following
<asp:LinkButton runat="server" OnClick="btnDownload_Click" Text="Download"/>
Your code behind will have the following
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
var fileInBytes = Encoding.UTF8.GetBytes("Your file text");
using (var stream = new MemoryStream(fileInBytes))
{
long dataLengthToRead = stream.Length;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType = "text/xml"; /// if it is text or xml
Response.AddHeader("Content-Disposition", "attachment; filename=" + "yourfilename");
Response.AddHeader("Content-Length", dataLengthToRead.ToString());
stream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
}
Response.End();
}
}
catch (Exception)
{
}
}
you can direct link the hyperlink with the file if you know the address but this is limited by the browser. eg. if pdf reader is installed on the client then the pdf will not be downloaded instead it will be shown. A good solution would be to have a seperate page for downloading files. just pass filename in querystring and in the pageload event just outpit the file in response stream.This way you can use url say dwnld.aspx?filename.ext
Now you can generate urls via the above logic.

Cannot hear audio from ASP.NET "Text to Speech" Application

in my asp.net project, I code below for a text to speech function.
in my page's c# file.
byte[] SpeakText(string text)
{
using (SpeechSynthesizer s = new SpeechSynthesizer())
{
using (MemoryStream ms = new MemoryStream())
{
s.SetOutputToWaveStream(ms);
s.Speak(text);
return ms.GetBuffer();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
Response.Write(SpeakText(TextBox1.Text));
}
}
but not hear the audio while run it.
How to solve the problem?
Try setting the response content type:
Response.ContentType = "audio/wav";
Also don't use Response.Write as it expects encoded characters. You need to write binary to avoid getting corrupt data:
Response.Clear();
Response.ContentType = "audio/wav";
Response.BinaryWrite(SpeakText(TextBox1.Text));
Response.End();
your code is executing on the server, not on the client machine.
Once you have generated the Speech output you should stream it down to the client (as a wav file for example), check this answer for a full example:
https://stackoverflow.com/a/1719867/559144

Resources