读写流我把byte数组长度设置成1000或2000时得到的文件总出错
private string down(string inUrl,string title)
{
//以字符流的形式下载文件
WebRequest objRequest = System.Net.HttpWebRequest.Create(inUrl);
try
{
BufferedStream buff = new BufferedStream(objRequest.GetResponse().GetResponseStream());
byte[] bytes = new byte[1024];//这里如果是1000或2000时有时得到的文件(大小5-6M左右)出错有时不出错
FileStream fs2 = new FileStream(title, FileMode.Create, FileAccess.Write);
BufferedStream bs2 = new BufferedStream(fs2);
while (buff.Read(bytes, 0, bytes.Length) > 0)
{
// buff.Read(bytes, 0, bytes.Length);
int aa = bytes.Length;
bs2.Write(bytes, 0, bytes.Length);
bs2.Flush();
}
buff.Close();
bs2.Close();
fs2.Close();
}
catch
{
title = "123";
}
return title;
}
------解决方案--------------------
int aa = bytes.Length;
bs2.Write(bytes, 0, bytes.Length);
就这两句出错,bytes.Length永远是你上面设定的固定值。而实际并不一定读取恰好等于数组长度的字节数。应该设定个表示实际读取的字节数的变量
int readByteNum;
while ((readByteNum = buff.Read(bytes, 0, bytes.Length)) > 0)
{
bs2.Write(bytes, 0, readByteNum);
bs2.Flush();
}