Implement "file download" in C#

Hi...

I am writing an application where I have a button. When the user clicks the button, data is read from a database and a text report is generated. Additionally, I want to have a file download dialog box appear to allow the user to save the report to his hard disk. I tried using the following:

   strFileName = Request.QueryString("file");   
   Response.ContentType = "application/octet-stream";
   Response.ContentType = "application/x-download";
   Response.AddHeader("Content-Disposition", "filename=" + strFileName);
   Response.WriteFile(Server.MapPath(strFileName));
   Response.End;

When I run the application , no dialog box appears, it tries to write to the server instead.

Can any body pls point out what is wrong. Or is there any other way to do this. Thanks.


Answer this question

Implement "file download" in C#

  • ilengyel

    Hi,

    as I understand your problem you want to download a file from the server. Look here in the Webclient Class:

    http://msdn.microsoft.com/library/default.asp url=/library/en-us/cpref/html/frlrfsystemnetwebclientclasstopic.asp

  • umit onal

    Hi,

    The WebClient is the easiest approach:


    WebClient myWebClient = new WebClient();
       try
       {
          myWebClient.DownloadFile(fromUrl, toFileName);
       }
       catch (WebException ex)
       {
          Result = ex.Message;
       }

     

    Regards,
    Vikram



  • El_Dibujante

    Try this code



    strFileName = Request.QueryString("file");   
       Response.Clear();
       Response.ContentType = "application/octet-stream";
       Response.ContentType = "application/x-download";
       Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
       Response.WriteFile(Server.MapPath(strFileName));
       Response.End();



     


     Regards,
    Saurabh Nandu
    www.MasterCSharp.com
    www.AksTech.com

  • Mendelt

    Hi,

    Thanks everybody for your help. The original code worked, of course with the Response.End(). The problem was in the file name.

    Regards,
    Kevin

  • Implement "file download" in C#