Search code examples
c#tcptcpclient

FileStream.Read() doesn't work with offset more than 0 in c#


I am working on a file transferring system in c#. The client reads the file into partitions and sends each partition to the server.

Each partition is 4096 bytes except for last partition which is the rest of the bytes. Data is sent over a TCP socket.

The problem is in the FileStream.Read() function because whenever offset is greater than 0, the function raises a System.ArgumentException. Here is the code:

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);

Solution

  • From the MSDN:

    offset

    The byte offset in array at which the read bytes will be placed.

    So your offset should always be zero