I am making a program that transfers a file to pieces over TCP. Now, every time I move the file a little to the end, it does not seem to be written, and therefore, if I try to transfer the image in the lower right corner, there are crashes . Now, my first idea was that when I read, transmit and write the last piece, which is less than the length of the buffer, I also write a lot of zeros. So I tried to resize the last buffer accordingly. Then I tried this using a small text file in which only HELLO WORLD is written, but when I write it and then open the file, it is empty.
Here is the read and send code, where range [0] is the first part, and range [1] is the last part:
byte[] buffer = new byte[DATA_BUFF_SIZE];
using (Stream input = File.OpenRead(file.Path))
{
Console.WriteLine("SENT PARTS # ");
for (int i = range[0]; i <= range[1]; i++)
{
Console.Write("PART " + i + ", ");
if (i == range[1])
{
buffer = new byte[input.Length - input.Position];
}
input.Position = i * DATA_BUFF_SIZE;
input.Read(buffer, 0, buffer.Length);
netStream.Write(buffer, 0, buffer.Length);
}
Console.WriteLine("LENGTH = " + input.Length);
}
here is the reception and recording code:
int bytesReceived = 0;
int index = partRange.First;
int partNum = 0;
byte[] receiveBuffer = new byte[BUFF_SIZE];
if (index == partRange.Last)
{
receiveBuffer = new byte[fileToDownload.Length - index * BUFF_SIZE];
}
while ((bytesReceived = netStream.Read(receiveBuffer, 0, receiveBuffer.Length)) > 0)
{
Console.Write("INDEX:" + index + ", ");
output.Position = index * BUFF_SIZE;
output.Write(receiveBuffer, 0, receiveBuffer.Length);
index++;
partNum++;
if (partNum > (partRange.Last - partRange.First))
{
break;
}
if (index == partRange.Last)
{
receiveBuffer = new byte[fileToDownload.Length - index * BUFF_SIZE];
}
}
Console.WriteLine();
? , .
, .