通过网络流发送字节数组时,最终文件中会出现额外的字符



发送一个字节数组

public static void SendFile(string path)
{
byte[] data = File.ReadAllBytes(path);
stream.Write(data, 0, data.Length);
}

获取字节数组

List<byte> list = new List<byte>();
byte[] data = new byte[64]; 
int bytes = 0;
do
{
bytes = stream.Read(data, 0, data.Length);
for (int i = 0; i < data.Length; i++)
{
list.Add(data[i]);
}
} while (stream.DataAvailable);
return list.ToArray();

创建文件

byte[] file = ReciveFile().ToArray();
File.WriteAllBytes(message, file);

显示额外的字符,如

之前之后

如何修复感谢

您需要检查读取了多少字节。否则,如果文件的长度不是64的整数倍,那么缓冲区的末尾可能包含垃圾。

do
{
bytes = stream.Read(data, 0, data.Length);
for (int i = 0; i < bytes; i++)  //use bytes, not data.Length
{
list.Add(data[i]);
}
} while (bytes > 0);

最新更新