string fileSrc = updateFileUrl + fileStr;//server's url
WebRequest webReq = WebRequest.Create(fileSrc);
WebResponse webRes = webReq.GetResponse();
long fileLength = webRes.ContentLength;
Stream srm = webRes.GetResponseStream();
StreamReader srmReader = new StreamReader(srm);
byte[] bufferbyte = new byte[fileLength];
int allByte = (int)bufferbyte.Length;
int startByte = 0;
while (fileLength > 0)
{
Application.DoEvents();
int downByte = srm.Read(bufferbyte, startByte, allByte);//提示这里出错.
if (downByte == 0) { break; };
startByte += downByte;
allByte -= downByte;
}
FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(bufferbyte, 0, bufferbyte.Length);
srm.Close();
srmReader.Close();
fs.Close();
webReq.Abort();
webRes.Close();
在srm.Read(bufferbyte, startByte, allByte)时出错.有点弄不懂为什么了.
你这样读数据过大造成缓冲区溢出了。
while (fileLength > 0)
{
Application.DoEvents();
int downByte = srm.Read(bufferbyte, startByte, allByte);//downByte变为allByte
if (downByte == 0) { break; };
startByte += downByte;//第一次循环后startByte变为allByte
allByte -= downByte;;//第一次循环后allByte变为0
}第二次循环可以进入,因为fileLength一直没变,都>0,这是循环中的第二行变为:
int downByte = srm.Read(bufferbyte, allByte, 0);//bufferbyte已满,无法再读,即使是0,这是安全性问题,下面附另一种方法。
string fileSrc = updateFileUrl + fileStr;//server's url
WebRequest webReq = WebRequest.Create(fileSrc);
WebResponse webRes = webReq.GetResponse();
long fileLength = webRes.ContentLength;
Stream srm = webRes.GetResponseStream();
StreamReader srmReader = new StreamReader(srm);
string html = srmReader.ReadToEnd(); using (StreamWriter sw = new StreamWriter(tempPath, true))
{
sw.Write(html);
}
srm.Close();
srmReader.Close();
webReq.Abort();
webRes.Close();
你的缓冲区大小是fileLength。
就没问题了,你试一下。
清除资源
还有其他程序程序导致
分包发送
控制每次send的时间间隔。
有必须的话可以采用异步响应的试,等收到对方的响应之后再传下一部分。
TCP的连接控制协议只能在一定范围内控制流量,一旦流量过大,超过其网络负载,时间一长,缓存空间不够的时候数据丢失
if(int downByte = srm.Read(bufferbyte, startByte, allByte))
{
fs.Write(bufferbyte, 0, downbyte);
}请看清楚fs.Write的参数啊... 我想你应该可以结贴了。