强制文件下载错误C#

时间:2015-09-25 20:40:11

标签: c# .net xml download

我有一个包含列表的页面,我可以在哪里下载XML文件,但是在XML文件下面有一个公司的服务器是页面的HTML。下载代码上的XML通常适用于安装了应用程序的所有服务器,但该服务器除外。下载文件的方法如下:

 public void StreamFileToBrowser(string sFileName, byte[] fileBytes, string ext)
    {
        HttpContext context = HttpContext.Current;
        context.Response.Buffer = false;
        context.Response.Clear();
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.AppendHeader("content-length", fileBytes.Length.ToString());
        context.Response.ContentType = "application/octet-stream";//string.Format("application/{0}", ext);
        context.Response.AppendHeader("content-disposition", "attachment; filename=" + sFileName);
        context.Response.BinaryWrite(fileBytes);           
    }

强行下载文件的其他方法是什么?

修改

当用户点击下载按钮时,会调用此方法。

2 个答案:

答案 0 :(得分:2)

将文件写入输出后。您应该通过以下方式结束响应:

context.ApplicationInstance.CompleteRequest();

这可以防止进一步写入响应。如果您将XML下载逻辑分离到单独的处理程序中,通常这不是必需的。但是当你有一些兼顾两者的逻辑时,你可能遇到问题。

答案 1 :(得分:0)

我使用以下方法解决了我的问题:

context.Response.Flush();
context.Response.Close();
context.Response.End();

最后。