C# 中的文件传输程序会在图像和无法打开的二进制文件上留下工件

本文关键字:二进制文件 传输 文件 程序 图像 | 更新日期: 2023-09-27 18:35:30

文本文件似乎没问题。以下是用于发送文件的代码:

System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
double done = 0;
double tot = info.Length;
double chunk = 8096;
while (done < tot)
{
    if (chunk > tot - done)
    {
        chunk = tot - done;
    }
    Byte[] buffer = new Byte[(int)chunk];
    reader.Read(buffer,(int)done,(int)chunk);
    sock.Send(buffer);
    done += chunk;
    statusTxt.Text = Math.Round(done / tot * 100, 2).ToString() + "%";
}

接收文件的代码非常相似:

private void ReceiveFile(string file, Socket sock,double size)
{
    while (done < size)
        {
            if (chunk > (size - done))
            {
                chunk = size - done;
            }
            Byte[] buffer = new Byte[(int)chunk];
            int count = sock.Receive(buffer);
            writer.Write(buffer);
            done += count;
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate()
            {
                foreach (TextBlock block in files.Items)
                {
                    if (block.Tag.ToString() == file)
                    {
                        block.Text = "Uploading " + file + "... 0% ("+done.ToString()+"/" + size.ToString() + ")";
                    }
                }
            });
        }
        writer.Flush();
        writer.Close();
    }

我看过很多关于图像伪影的帖子,但所有问题都涉及字节被编码为文本。我相信我已经避免了这个问题。我在整个过程中使用字节数组,并跟踪正在读取的字节数,但图像最终仍然损坏。我检查了文件,它们在客户端和服务器上包含相同的确切字节数,所以服务器上发生了一些事情,但它只是不正确。代码有什么问题,或者可能是服务器问题?

C# 中的文件传输程序会在图像和无法打开的二进制文件上留下工件

您似乎大多忽略了实际发送/接收的字节数。特别是writer.Write(buffer);写入整个缓冲区,无论它之前是否完全由sock.Receive(buffer);填充。