使用此方法从流中正确读取:
public static void ReadWholeArray (Stream stream, byte[] data)
{
int offset=0;
int remaining = data.Length;
while (remaining > 0)
{
int read = stream.Read(data, offset, remaining);
if (read <= 0)
throw new EndOfStreamException
(String.Format("End of stream reached with {0} bytes left to read", remaining));
remaining -= read;
offset += read;
}
}
您可能希望首先将文件的长度写入流中(例如作为 int),例如,
服务器端:
server.Write(clientData.Length)
server.Write(clientData);
客户端:
byte[] size = new byte[4];
ReadWholeArray(stream, size);
int fileSize = BitConverter.ToInt32(size, 0);
byte[] fileBytes = new byte[fileSize];
ReadWholeArray(stream, fileBytes);
有关从流中读取的更多信息,请参阅http://www.yoda.arachsys.com/csharp/readbinary.html。