0

I have this download function :

    protected void ExportData(string fileName, string fileType, string path)
    {
        System.IO.StreamReader sr = new System.IO.StreamReader(path);


        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
        Response.Charset = "";
        Response.ContentType = fileType;
        Response.Output.Write(sr.ReadToEnd());
        Response.Flush();
        Response.End();

    }

I use it :

    ExportData("infoMandat_" + g.NO_MANDAT + ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", g.URL_infoMandat);

But the file is always empty OR corrupted...

Probably because i'm reading it with a plain StreamReader

The solution proposed in the answer is the function .Transmit(), question marked as duplicate is absolutely not the solution to THIS question.

Antoine Pelletier
  • 3,164
  • 3
  • 40
  • 62

1 Answers1

2

You do not need to use Stream if the file is already in the website folder. You can use either use TransmitFile or WriteFile.

Please make sure path is a correct folder location. For example, C:\inetpub\wwwroot\samplewebsite\

protected void ExportData(string fileName, string fileType, string path)
{
    Response.ContentType = fileType;
    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
    Response.TransmitFile(Path.Combine(path + fileName));
    Response.End();
}

// Usage
ExportData("infoMandat_" + g.NO_MANDAT + ".docx", 
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document", 
    g.URL_infoMandat);
Win
  • 61,100
  • 13
  • 102
  • 181
  • `TransmitFile()` is what i was looking for, i used `.Output.Write()` when it was plain text, DOCX files are not plain text... of course. Thanks a lot ! – Antoine Pelletier Sep 21 '17 at 16:58