c# - 下载文件引发异常

标签 c# asp.net exception

我有一个带有 GridView 的网络表单,其中以文件名作为列。如果单击文件名,将向用户显示一个打开/保存对话框。大多数情况下,这会引发异常并显示错误消息 - 远程主机关闭了连接。错误代码为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();
}

问题的根源是什么?

最佳答案

远程主机关闭了连接。错误代码为 0x80072746。 - 如果浏览器在您的服务器结束连接之前未完成下载,则会引发此异常。

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

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

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

关于c# - 下载文件引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6814432/

相关文章:

c# - 在 C# 中检测空白图像(预期的图像是条形码)

c# - Excel进程没有关闭

MySQL TRIGGER NEW.date=NOW() 在除 `id` 和 `name` 之外的任何列更新

c# - 使用 Flurl GetResponseJson<TError>() 进行单元测试代码

c# - 使用默认值初始化队列或堆栈?

c# - 与许多用户读取/写入完全相同的 xml 文件有关的问题

c# - ASP .NET Button 事件处理程序不会在第一次单击时触发,而是在 PostBack 后的第二次单击时触发

c++ - 如何在 Visual Studio 2005 (C++) 中声明复杂变量

java - 编译器如何识别从未从 Java 中的 try 语句体中抛出异常

java - 我在onAttach方法的AlertDialog类中遇到错误CastClassException