代码.问题是像 .txt 文件这样的小文件可以正确传输,但不能像图像、文档、pdf、ppt 这样的大文件.有时代码运行良好,但大多数时候它传输的数据量较少.I am transferring files using c#. I have used this code. The problem is small files like .txt files are transferred correctly but not big files like images, documents, pdf, ppt. Sometimes code works fine but most of the times it transfers less amount of data.服务器代码:Socket clientSock = sock.Accept();byte[] clientData = new byte[1024 * 50000];int receivedBytesLen = clientSock.Receive(clientData);int fileNameLen = BitConverter.ToInt32(clientData, 0);string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + "/" + fileName, FileMode.Append));bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);bWrite.Close();clientSock.Close();客户代码:byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);byte[] fileData = File.ReadAllBytes(filePath + fileName);byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);fileNameLen.CopyTo(clientData, 0);fileNameByte.CopyTo(clientData, 4);fileData.CopyTo(clientData, 4 + fileNameByte.Length);clientSock.Connect(ipEnd);clientSock.Send(clientData);clientSock.Close();完整代码在上面的链接中给出.我也看过这个帖子,但这没有帮助.Complete code is given in the above link. I have also seen this post but this is not helpful.推荐答案正如 CodeCaster 的 回答的那样 Socket.Receive(),它并不总是返回发送给它的所有数据. 这是 100% 正确并经过测试,但发送文件大小的下一步不起作用,我找到了一个简单且正确的解决方案.As CodeCaster's answered that Socket.Receive(), it doesn't always return all data that gets sent to it. This is 100% correct and tested but the next step of sending the file size is not working, I found an easy and correct solution.Socket.Receive() 方法获取接收数据将被复制到的字节数组,并返回接收到的字节数.所以我们可以很容易地循环它,直到接收到的字节数为 0.Socket.Receive() method takes the byte array in which received data will be copied and returns the number of bytes received. So we can easily loop it till bytes received are 0.byte[] tempData = new byte[1024 * 5000];BinaryWriter bWrite = null;int bytes_received;int fileNamelength = 0;bool isFirstPacket = true;do{ bytes_received = clientSock.Receive(tempData); if(isFirstPacket) { isFirstPacket = false; int fileNameLen = BitConverter.ToInt32(tempData, 0); string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen); bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append)) bWrite.Write(tempData, 4 + fileNameLength, bytes_received - 4 - fileNamelength); } else bWrite.Write(tempData, 0, bytes_received);}while (bytes_received != 0); 这篇关于C#中的文件传输问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-25 13:06