FileStream.Read()不适用于c#中的偏移量大于0

时间:2018-01-19 03:18:18

标签: c# tcp tcpclient

我正在 c#中处理文件传输系统。客户端将文件读入分区并将每个分区发送到服务器。

每个分区都是4096字节,除了最后一个分区,这是其余的字节。数据通过 TCP 套接字发送。

问题在于FileStream.Read()函数,因为只要offset大于0,该函数就会引发System.ArgumentException。这是代码:

string fileSize = "0";
FileStream f = null;
try
{
    f = File.Open(path, FileMode.Open, FileAccess.Read);
    fileSize = f.Length.ToString();
}
catch (Exception e)
{ }
// send partition count to server
int partitionCount = int.Parse(fileSize) / 4096;
int lastPartitionSize = (int.Parse(fileSize) - (partitionCount * 4096));
Thread.Sleep(20);
sendData(partitionCount.ToString());
Thread.Sleep(20);
sendData(lastPartitionSize.ToString());
Thread.Sleep(20);
for (int i = 0; i < (partitionCount); i++)
{
    byte[] data = new byte[4096];
    int offset = (4096 * i);
    Console.WriteLine("Partition: " + (i+1) + "  |  Offset: " + offset + "  |  Bytes Left: " + (f.Length - (4096*i)));
    f.Read(data, offset, 4096); // problem is RIGHT HERE
    sendRawData(data);
}
byte[] lastData = new byte[lastPartitionSize];
f.Read(lastData, (4096 * partitionCount), lastPartitionSize);
sendRawData(lastData);

1 个答案:

答案 0 :(得分:1)

来自MSDN:

  

偏移

     

数组中的字节偏移量,读取字节将放在该位置。

所以你的偏移应该总是为零