2

I have a piece of code that generates different types of files: text, excel, etc.

For Excel files, for instance, all browsers prompt the user to download and/or open their default software to handle the file type. That's the expected behavior. But for the text files, all browsers "assume" the user wants to open it on a new tab.

I want to force the download, because the text file is large (30MB+). I don't want the user to right click and "save as...". How can I do this in C#? Right now my code is returning a signed URL:

return Redirect(signedURL.AbsoluteUri);
user692942
  • 16,398
  • 7
  • 76
  • 175
tfrege
  • 91
  • 3
  • 9
  • possible duplicate of [Make a file open in browser instead of downloading it](http://stackoverflow.com/questions/19411335/make-a-file-open-in-browser-instead-of-downloading-it) – crthompson Nov 26 '14 at 16:46
  • I believe some prior answers on this may help. [check this out](http://stackoverflow.com/questions/525364/how-to-download-a-file-from-a-website-in-c-sharp) – Jimmy Smith Nov 26 '14 at 16:46

3 Answers3

2

Try the following:

this.Response.ContentType = "text/plain";
this.Response.AddHeader("content-disposition", "attachment;filename=" + file);

Force download ASP.Net What content type to force download of text response?

Community
  • 1
  • 1
Hungry Beast
  • 3,677
  • 7
  • 49
  • 75
0

Use this to force download of file from an external link

    <script language="c#" runat="server">
        protected void Button1_Click1(object sender, EventArgs e)
        {
string k="file full path 'eg: http://something.com/test.pdf' ";
            Response.ContentType = "Application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf");

            WebClient wc = new WebClient();
            byte[] myDataBuffer = wc.DownloadData(k);
            Response.BinaryWrite(myDataBuffer);
            Response.End();
        }
    </script>
cactus
  • 1
0

I spent three days figuring this out, and it came down to the way HTML encoding is done, from the server. Works great from a local PC, but as soon as you've ported your project into a server, using IIS, it kept continually failing with "Stream has closed" or a weird "H_Visual" filename as the file to SAVE AS, in the dialog box.

Here is my full code:

public override void btnFILEOPEN_Click(object sender, EventArgs args)
{
    // Get the name of the file to be uploaded and 
    // the location where the file needs to be opened from
    // in my case it's a "../Data" folder within the IIS root folder.
    string fileName = this.AttachmentFilePath.Text;
    bool fileExists = System.IO.File.Exists((this.Page.Server.MapPath("..\\Data") + ("\\" + fileName)));
    if (fileExists)
    {
        // Set up file stream object.
        System.IO.FileStream fs;
        fs = new System.IO.FileStream((this.Page.Server.MapPath("..\\Data") + ("\\" + fileName)), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
        string fullFileName = (this.Page.Server.MapPath("..\\Data") + ("\\" + fileName));
        try
        {
            // Read the contents of the file.
            int bufSize = ((int)(fs.Length));
            byte[] buf = new byte[bufSize];
            int bytesRead = fs.Read(buf, 0, bufSize);

            // Set up parameters for file download.
            this.Page.Response.Clear();
            this.Page.Response.ContentType = "application/octet-stream";
            this.Page.Response.AddHeader("Content-Disposition", ("attachment;filename=" + HttpUtility.UrlEncode(fileName)));

            // Download the file.
            this.Page.Response.OutputStream.Write(buf, 0, bytesRead);
            this.Page.Response.Flush();
        }
        catch (Exception ex)
        {
            // Report the error message to the user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "UNIQUE_SCRIPTKEY", ex.Message);
        }
        finally
        {
            fs.Close();
        }
    }
    else
    {
        this.Page.Response.Write("File cannot be found to download");
    }
}

The magic was simply in the HttpUtility.UrlEncode() method. It converted my file name into something IIS understands, not us dumb humans!

Fandango68
  • 4,461
  • 4
  • 39
  • 74