Antoine Pelletier
Antoine Pelletier

Reputation: 3316

Download a DOCX file using ASP.net WEB FORM

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.

Upvotes: 0

Views: 2074

Answers (1)

Win
Win

Reputation: 62260

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);

Upvotes: 2

Related Questions