使用ASP.net WEB FORM下载DOCX文件

时间:2017-09-21 16:08:28

标签: c# asp.net webforms

我有这个下载功能:

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

    }

我用它:

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

但文件总是空的或已损坏......

可能是因为我用普通的StreamReader

来阅读它

答案中提出的解决方案是函数.Transmit(),标记为重复的问题绝对不是这个问题的解决方案。

1 个答案:

答案 0 :(得分:1)

如果文件已在网站文件夹中,则无需使用Stream。您可以使用TransmitFileWriteFile

请确保path是正确的文件夹位置。例如,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);