下载文件会引发异常

时间:2011-07-25 10:00:14

标签: c# asp.net exception

我有一个带有GridView的webform,它有一个文件名作为列。如果单击文件名,则会向用户显示“打开/保存”对话框。大多数情况下,这会引发错误消息 - The remote host closed the connection. The error code is 0x80072746

除Firefox之外,任何其他浏览器中的用户都看不到此错误。在Firefox中,所选文件会在页面本身上呈现,过了一段时间后,页面会出错 - 连接已重置。

我正在通过将文件分解为数据包来下载文件,因为我必须确定文件是否已完全下载,然后将此条目写入数据库表。

我已将Buffer="false"放在页面指令中,但它不起作用。 我尝试从代码中删除Response.Flush(),但无济于事。

我的文件下载代码如下:

LinkButton btnTemp = (LinkButton)sender;
GridViewRow row = (GridViewRow)btnTemp.NamingContainer;
HiddenFieldFullFileName.Value = row.Cells[1].Text;

FileInfo file = new FileInfo(HiddenFieldFullFileName.Value);
if (file.Exists)
{
    string filePath="", fileName="";

    //store filepath and filename in separate variables
    string[] temp = row.Cells[1].Text.Split('\\');
    for (int j = 0; j < temp.Length; j++)
    {
        if (j < (temp.Length - 1))
            if(j==0)
              filePath = filePath + temp[j];
            else
              filePath = filePath + "\\" + temp[j];
        else
            fileName = temp[j];

    }
    FileStream myFile = new FileStream(row.Cells[1].Text, FileMode.Open,FileAccess.Read, FileShare.ReadWrite);

    //Reads file as binary values
    BinaryReader _BinaryReader = new BinaryReader(myFile);

    long startBytes = 0;
    string lastUpdateTimeStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
    string _EncodedData = HttpUtility.UrlEncode(fileName, Encoding.UTF8) + lastUpdateTimeStamp;

    //Clear the content of the response
    Response.Clear();
    Response.Buffer = false;
    Response.AddHeader("Accept-Ranges", "bytes");
    Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
    Response.AppendHeader("Last-Modified", lastUpdateTimeStamp);

    //Set the ContentType
    Response.ContentType = "application/octet-stream";

    //Add the file name and attachment,
    //which will force the open/cancel/save dialog to show, to the header
    Response.AddHeader("Content-Disposition", "attachment;filename=" + file.Name);

    //Add the file size into the response header
    Response.AddHeader("Content-Length", (file.Length - startBytes).ToString());
    Response.AddHeader("Connection", "Keep-Alive");

    //Set the Content Encoding type
    Response.ContentEncoding = Encoding.UTF8;

    //Send data
    _BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin);

    //Dividing the data in 1024 bytes package
    int maxCount = (int)Math.Ceiling((file.Length - startBytes + 0.0) / 1024);

    //Download in block of 1024 bytes
    int i;
    for (i = 0; i < maxCount && Response.IsClientConnected; i++)
    {
        Response.BinaryWrite(_BinaryReader.ReadBytes(1024));
        Response.Flush();
    }

    //compare packets transferred with total number of packets
    if (i >= maxCount)
    {
        //get the IP address of user
        string ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (ipAddress == null)
        {
            ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

        //write the download information to database table

    }


    //Close Binary reader and File stream
    _BinaryReader.Close();
    myFile.Close();
}

问题的根源是什么?

2 个答案:

答案 0 :(得分:2)

The remote host closed the connection. The error code is 0x80072746. - 如果浏览器在服务器结束连接之前未完成下载,则会引发此异常。

这可能是因为您在Response.BinaryWrite后编写文件和sql的奇怪方案。

如果你想创建一些自定义服务器进行下载,你还应该创建自定义客户端 - 浏览器不知道你的代码,他可能会丢失他的连接。
此外,您对传输字节的检查没有意义 - 您无法了解客户端接受的字节

所以我强烈推荐Response.WriteFile(filename)

答案 1 :(得分:1)

我认为你可以使用Response.WriteFile,你应该使用你已经创建的FileInfo对象。代码:

        LinkButton btnTemp = (LinkButton)sender;
        GridViewRow row = (GridViewRow)btnTemp.NamingContainer;
        HiddenFieldFullFileName.Value = row.Cells[1].Text;

        FileInfo file = new FileInfo(HiddenFieldFullFileName.Value);
        if (file.Exists)
        {

            string lastUpdateTimeStamp = file.LastWriteTimeUtc.ToString("r");
            string _EncodedData = HttpUtility.UrlEncode(file.Name, Encoding.UTF8) + lastUpdateTimeStamp;

            //Clear the content of the response
            Response.Clear(); 
            Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
            Response.AppendHeader("Last-Modified", lastUpdateTimeStamp);

            //Set the ContentType
            Response.ContentType = "application/octet-stream"; 

            //Add the file name and attachment,
            //which will force the open/cancel/save dialog to show, to the header
            Response.AddHeader("Content-Disposition", "attachment;filename=" + file.Name); 

            //Send data
            Response.WriteFile(file.FullName);
            Response.End();
        }

如果您知道特定的contenttype而不是“application / octet-stream”,则可以将其更改为文件的mimetype(有关示例,请参阅here