1

I have a word document in my server, that I want to send to my client. Actually I want them to download that file. I am creating that file in runtime, and I want to delete it after they download it from my server. I'm trying this scenario locally. After the creation of file, my server sends it to client. In web browser I see this:

enter image description here

I don't want this. I want web browser to open save file dialog. I want client to download real file. Here is my code :

           Guid temp = Guid.NewGuid();
           string resultFilePath = Server.MapPath("~/formats/sonuc_" + temp.ToString()  + ".doc");
            if (CreateWordDocument(formatPath, resultFilePath , theLst)) {

                Response.TransmitFile(resultFilePath);

                Response.Flush();

                System.IO.File.Delete(resultFilePath);

                Response.End();
            }
MilesDyson
  • 738
  • 1
  • 11
  • 33

2 Answers2

7

This snippet should do the trick, but notice that this will result in loading the whole file into the memory (of the server).

private static void DownloadFile(string path)
{
    FileInfo file = new FileInfo(path);
    byte[] fileConent = File.ReadAllBytes(path);

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", file.Name));
    HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.BinaryWrite(fileConent);
    file.Delete();
    HttpContext.Current.Response.End();
}
Sigma Bear
  • 931
  • 5
  • 7
1

What you want is not an .aspx file (which is a web-page) but an .ashx which can provide the data you need, and set the content-disposition. See this question for an example (here using PDF-downloads):

Downloading files using ASP.NET .ashx modules

You might also try to set the correct content type / mime type for Word, perhaps like the following, or you might take a look at this question.

response.ContentType = "application/msword";
response.AddHeader("Content-Disposition", "attachment;filename=\"yourFile.doc\"");
Community
  • 1
  • 1
Kjartan
  • 18,591
  • 15
  • 71
  • 96
  • Since you've metioned, I've been following this example: http://davidarodriguez.com/blog/2013/05/29/downloading-files-from-a-server-to-client-using-asp-net-when-file-size-is-too-big-for-memorystream-using-generic-handlers-ashx/ But have to pass file name to .ashx class? – MilesDyson Apr 01 '14 at 06:34
  • 1
    You could pass a name to the .ashx, or make the ashx fetch the file from somewhere.. The main point is that you have to specify what type of data you are transferring to the client / browser, and how you want it to handle that data, and this is done by specifying content type and header. – Kjartan Apr 01 '14 at 06:39