简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM