下载图像 - 分块编码 - 服务器不发送零长度块

时间:2012-03-01 01:37:38

标签: c# asp.net .net httpwebrequest

我正在下载一个Tiff文件并使用下面的代码将其保存到我的本地临时目录中。使用Chunked编码发送文件。该文件已下载,然后写得很好,但我的应用程序一直运行,直到抛出异常:Unable to read data from the transport connection: The connection was closed.

使用Fiddler,我发现服务器没有发送零长度的块,而只是关闭连接。如何检测何时到达文件结尾并结束程序?

        CookieContainer cookieJar = new CookieContainer();

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileUrl.AbsoluteUri);
        request.Credentials = CredentialCache.DefaultCredentials;
        request.PreAuthenticate = true;
        request.CookieContainer = cookieJar;

        request.AllowWriteStreamBuffering = true;
        request.Timeout = 10000;


        using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
        {
            byte[] buffer = new byte[32768];

            using (Stream input = httpResponse.GetResponseStream())
            {
                using (FileStream fs = new FileStream(tempPath + "test_name.tif", FileMode.Create, FileAccess.Write))
                {
                    int bytesRead;

                    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, bytesRead);                           
                    }
                }
            }           
        }

0 个答案:

没有答案