开发者

Download text as a file from a webpage

开发者 https://www.devze.com 2023-01-15 02:21 出处:网络
I\'m downloading text from a website and I want to have the user be able to save it as a file. So, I have the following code that does just that.

I'm downloading text from a website and I want to have the user be able to save it as a file. So, I have the following code that does just that.

protected void DownloadFile(string fileName, string content)
{
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.ContentType = "text/plain";
    Response.Write(content);
    Response.End();
}

The problem I am having is that I get an exception after this code ru开发者_StackOverflow中文版ns. I believe it's due to the fact that I call Response.End(). So, every time a user downloads a file it redirects them to the generic error page because all generic exceptions redirect to that page.

Any ideas on how I can write text out to a file and not get this error? If I remove Response.End() I get my text and then the rest of the HttpResponse text, but I don't get the error.

Thanks.


First, if this code is inside a .ASPX file, you need to move it out to a .ASHX file. Second, after you've moved to .ASHX you can simply write to the output stream and be done, you shouldn't need a Response.End();

This is the link I started with: http://dotnetperls.com/ashx-handler -- there isn't much to it. It simply removes a bunch of the asp.net "page" overhead.


Ideally you should have a page with a list, and a link/button to your "download.ashx" file. Then pass it a record id on the query string so it can do the lookup and response.write calls.


Don't call Response.End(). There is still code to be run server-side after you have populated the headers whether you intend to or not. Instead consider using Response.Flush() and allowing the page to complete. Another alternative would be to use a HttpHandler (ashx) file instead of an aspx/ascx file. This will give you more basic access to the Response so you should be able to end without repercussion.


Maybe you want to call Response.Output.Write() instead?

0

精彩评论

暂无评论...
验证码 换一张
取 消