c# – 将文件读入数组时出错
发布时间:2020-12-15 04:18:53 所属栏目:百科 来源:网络整理
导读:我在循环的第二次迭代中得到以下错误: 偏移量和长度超出了数组的范围,或者计数大于从索引到源集合末尾的元素数. 这是我的循环 FileStream fs = new FileStream("D: 6.Total Eclipse Of The Moon.mp3",FileMode.Open); byte[] _FileName = new byte[1024];
我在循环的第二次迭代中得到以下错误:
偏移量和长度超出了数组的范围,或者计数大于从索引到源集合末尾的元素数. 这是我的循环 FileStream fs = new FileStream("D: 6.Total Eclipse Of The Moon.mp3",FileMode.Open); byte[] _FileName = new byte[1024]; long _FileLengh = fs.Length; int position = 0; for (int i = 1024; i < fs.Length; i += 1024) { fs.Read(_FileName,position,Convert.ToInt32(i)); sck.Client.Send(_FileName); Thread.Sleep(30); long unsend = _FileLengh - position; if (unsend < 1024) { position += (int)unsend; } else { position += i; } } fs.Close(); } fs.Length = 5505214 解决方法
在第一次迭代中,你正在打电话
fs.Read(_FileName,1024); 那很好(虽然为什么你在int上调用Convert.ToInt32,我不知道.) 在第二次迭代中,您将要打电话 fs.Read(_FileName,2048); 它试图读入从位置开始的_FileName字节数组(非零)并获取最多2048个字节.字节数组只有1024个字节长,因此无法工作. 其他问题: >您尚未使用using语句,因此在例外情况下,您将使流保持打开状态 您的代码应该看起来更像这样: using (FileStream fs = File.OpenRead("D: 6.Total Eclipse Of The Moon.mp3")) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fs.Read(buffer,buffer.Length)) > 0) { sck.Client.Send(buffer,bytesRead); // Do you really need this? Thread.Sleep(30); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |