整个方法代码如下:
public static bool DownLoadFile(string serverFile, string localFile)
{
try
{
WebRequest request = WebRequest.Create(serverFile);
WebResponse response = request.GetResponse();
long fileLength = response.ContentLength;
byte[] buffer = new byte[fileLength];
long bufferLength = fileLength;
int maxReadCount = bufferLength > int.MaxValue ? int.MaxValue : buffer.Length;
int startPos = 0;
using (Stream stream = response.GetResponseStream())
{
while (bufferLength > 0)
{
int downByte = stream.Read(buffer, startPos, maxReadCount);
if (downByte <= 0) { break; }
startPos += downByte;
bufferLength -= downByte;
maxReadCount -= downByte;
}
using (FileStream fs = new FileStream(localFile, FileMode.Create, FileAccess.Write))
{
fs.Write(buffer, 0, buffer.Length);
stream.Close();
fs.Close();
}
}
return true;
}
catch (Exception ex)
{
Utility.GetInstance().Logger.Error("下载文件出错:"+ex.Message);
return false;
}
}
我看不明白的有两个地方:
1,int maxReadCount = bufferLength > int.MaxValue ? int.MaxValue : buffer.Length;
maxReadCount为什么取最小值:
2,如图,为什么越到后边往buffer中写入的数据越小?
飘过...同求答案..
分块下载,什么取最小值?int.maxvalue是最大值。。你可以查下?:操作符,你可以单步调试下。
程序错误。本想实现读取超大文件的
请问该怎么改写这段代码呢?麻烦你把改后的代码发给我好吗?