Stream.Read return System.IO.IOException

Stream.Read return System.IO.IOException

我正在尝试使用以下代码下载大型 zip (560MB):

DateTime startTime = DateTime.UtcNow;
WebRequest request = WebRequest.Create("https://report-demo.eyeq.tech/download/Downloads.zip");
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
    using (Stream fileStream = new FileStream("Downloads.zip", FileMode.Open, FileAccess.ReadWrite))
    {
        byte[] buffer = new byte[4096];
        int bytesRead = responseStream.Read(buffer, 0, 4096);
        while (bytesRead > 0)
        {
            fileStream.Write(buffer, 0, bytesRead);
            DateTime nowTime = DateTime.UtcNow;
            if ((nowTime - startTime).TotalMinutes > 5)
            {
                throw new ApplicationException("Download timed out");
            }
            bytesRead = responseStream.Read(buffer, 0, 4096);
        }
    }
}

但是下载几秒钟后,程序返回 System.IO.IOException: 'The decryption operation failed, see inner exception.' 并且内部异常是:Win32Exception: The specified data could not be decrypted
编辑: 完整的例外是:

Exception thrown: 'System.IO.IOException' in System.dll
System.IO.IOException: The decryption operation failed, see inner exception. ---> System.ComponentModel.Win32Exception: The specified data could not be decrypted
   --- End of inner exception stack trace ---
   at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at WpfApp1.MainWindow.<Download>d__1.MoveNext() in D:\vinh.ngo\Project\WpfApp1\MainWindow.xaml.cs:line 53

我无法重现此问题

var client=new System.Net.Http.HttpClient();
var url="https://report-demo.eyeq.tech/download/Downloads.zip";
using var stream=await client.GetStreamAsync(url);
using var fi=File.Create(@"c:\somepath.zip");
//Set up a 10" timeout
var cts=new CancellationTokenSource(TimeSpan.FromSeconds(10));
//Copy the data directly
await stream.CopyToAsync(fi,cts.Token);

或这个

var req=System.Net.WebRequest.Create(url);
using var response = req.GetResponse();
using var stream = response.GetResponseStream();
using var fi=File.Create(@"c:\somepath.zip");
//Set up the timeout
var cts=new CancellationTokenSource(TimeSpan.FromSeconds(10));
//Store the data
await stream.CopyToAsync(fi,cts.Token);
Console.WriteLine("Finished");

在 .NET Core 3.1 中,WebRequest 使用 HttpClient,因此这些片段之间没有太大区别。

此代码中唯一 encrypts/decrypts 数据是 SSL 连接。出现解密错误意味着连接受到某种影响。也许 服务器 断开了连接,导致不完整的包解密失败?或者连接中断,部分数据丢失?是否使用了 Fiddler 或其他一些调试代理?

更新

I changed to LAN and it worked 所有 Wi-Fi 连接都以某种方式失败。也许信号很弱,或者在同一个频道上发出嘈杂的邻居信号,或者电信公司的廉价路由器出于恶意决定丢弃一些包裹。咖啡馆中超负荷工作的路由器可能 CPU 无法处理所有连接,因此它会在一段时间后开始丢弃低优先级包