title: asp.net let user download file with save dialog
body: <p>I am having some problems with downloading files with the save dialog. </p>
  
  <p>My code executes with no errors but no save dialog shows up. Not in FF, not in chrome and not in IE. The attachment can have the following extensions: <code>.jpg,.jpeg,.png,.bmp,.pdf,.txt,.docx</code>. That's why I use <code>Response.ContentType = "application/octet-stream";</code> (see in code below). </p>
  
  <pre><code>    protected void btnDownload_OnCommand(object sender, CommandEventArgs e)
      {
          //Get the attachment to download from the webservice
          RCX.AddressAttachment attachment = ShopClient.GetAddressAttachment(ServiceContext,
              new AddressAttachmentCriteria()
              {
                  Id = (string) e.CommandArgument //= AttachmentID
              });
  
          //Get a random filename
          var fileName = string.Format("{0}{1}", Guid.NewGuid(), attachment.FileExtension);
  
          //Get the physicalPath to save the file
          var physicalPath = string.Format(@"{0}\Attachments\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
              fileName);
  
          //Get the webpath to navigate to the file
          var webPath = string.Format("{0}Attachments/{1}", Misc.BaseUrl(Request.Url), fileName);
  
          //Create file if not exists
          using (new FileStream(physicalPath, FileMode.OpenOrCreate))
          {
          }
  
          //Write bytes to file
          System.IO.File.WriteAllBytes(physicalPath, attachment.Attachment);
  
  
          var fileInfo = new FileInfo(physicalPath);
  
          //Try to open the save dialog, what is wrong here?
          Response.Clear();
          Response.ContentType = "application/octet-stream";
          Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0};", fileName));
          Response.AddHeader("Content-Length", fileInfo.Length.ToString());
          Response.WriteFile(physicalPath);
          Response.End();   
      }
  </code></pre>
  
  <p>The file exists after executing the <code>WriteAllBytes(string path, byte[] bytearray)</code> method. 
  If I navigate to the webPath in my code, I can also see the file in the browser (see code below). </p>
  
  <pre><code>        Response.Redirect(webPath);
  </code></pre>
  
  <p>What could I be doing wrong?</p>
  
  <p>Many thanks.</p>