我在循环的第二次迭代中得到以下错误:
Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
这是我的循环
FileStream fs = new FileStream("D:\\06.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
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 12
在第一次迭代中,你正在打电话
fs.Read(_FileName, 0, 1024);
Run Code Online (Sandbox Code Playgroud)
这很好(但你为什么要叫Convert.ToInt32上int,我不知道.)
在第二次迭代中,您将要打电话
fs.Read(_FileName, position, 2048);
Run Code Online (Sandbox Code Playgroud)
它试图读入_FileName从position(非零)开始的字节数组并获取最多2048个字节.字节数组只有1024字节长,所以不能可能工作.
其他问题:
using语句,因此在例外情况下您将保持流打开状态Read,这意味着您不知道实际读取了多少缓冲区您的代码应该看起来更像这样:
using (FileStream fs = File.OpenRead("D:\\06.Total Eclipse Of The Moon.mp3"))
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
sck.Client.Send(buffer, 0, bytesRead);
// Do you really need this?
Thread.Sleep(30);
}
}
Run Code Online (Sandbox Code Playgroud)