由于您没有发布任何代码,我将按照“我的方式”编写代码部分,但您在阅读后应该有所了解。
首先在两端(客户端和服务器)上,您应该应用统一协议,该协议将描述您发送的数据。示例可能是:
[3Bytes - ASCII 扩展名][4Bytes - lengthOfTheFile][XBytes - fileContents]
然后在您的发件人中,您可以根据协议接收数据,这意味着首先您读取 3 个字节以确定文件格式,然后读取 4 个字节,这基本上会告诉您传入的文件有多大。最后,您必须读取内容并将其直接写入文件。示例发件人可能如下所示:
byte[] extensionBuffer = new byte[3];
if( 3 != networkStream.Read(extensionBuffer, 0, 3))
return;
string extension = Encoding.ASCII.GetString(extensionBuffer);
byte[] lengthBuffer = new byte[sizeof(int)];
if(sizeof(int) != networkStream.Read(lengthBuffer, 0, 3))
return;
int length = BitConverter.ToInt32(lengthBuffer, 0);
int recv = 0;
using (FileStream stream = File.Create(nameOfTheFile + "." + extension))
{
byte @byte = 0x00;
while( (@byte = (byte)networkStream.ReadByte() ) != 0x00)
{
stream.WriteByte(@byte);
recv++;
}
stream.Flush();
}
在发送方部分,您可以读取文件扩展名,然后打开文件流获取流的长度,然后将流长度发送到客户端并将每个字节从FileStream“重定向”到networkStream。这可能看起来像:
FileInfo meFile = //.. get the file
byte[] extBytes = Encoding.ASCII.GetBytes(meFile.Extension);
using(FileStream stream = meFile.OpenRead())
{
networkStream.Write(extBytes, 0, extBytes.Length);
networkStream.Write(BitConverter.GetBytes(stream.BaseStream.Length));
byte @byte = 0x00;
while ( stream.Position < stream.BaseStream.Length )
{
networkStream.WriteByte((byte)stream.ReadByte());
}
}
这种方法很容易实现,如果您想发送不同的文件类型,不需要大的改动。它缺少一些验证器,但我认为您不需要此功能。