我正在尝试通过 webclient 下载文件,代码如下所示。问题是,如果我多次收到连续的 404 响应,我的服务器会达到 100% 并且查看事件日志会告诉我发生了堆栈溢出。这里的“count”变量是为了避免 0 字节文件,count404 是为了 404 响应。
int count = 0; int count404 = 0;
public Stream DownloadFileThroughWebClient(string strFilePath)
{
try
{
if (count >= 120 || count404 >= 30)
{
count = 0;
count404 = 0;
return null;
}
System.Threading.Thread.Sleep(1000);
System.Net.WebClient wc = new System.Net.WebClient();
var v = wc.DownloadData(strFilePath);
Stream FileToSave = new MemoryStream(v);
byte[] bytes = new byte[FileToSave.Length];
int numBytesToRead = (int)FileToSave.Length;
if (numBytesToRead > 0)
{
count = 0;
count404 = 0;
return FileToSave;
}
else
{
count++;
count404 = 0;
return DownloadFileThroughWebClient(strFilePath);
}
}
catch (Exception ex)
{
count++;
count404++;
return DownloadFileThroughWebClient(strFilePath);
}
}
提前致谢。