求助C#文件传输,请高手赐教……
欲实现一个类似QQ传文件一个网络文件传输模块,以下是实现文件传输模块功能的代码,但还存在一个亟待解决的问题——在接受端是一次性写入的,这就导致了当传输大文件时内存溢出的现象,请各位高手赐教,如何实现像QQ或飞秋、飞鸽那样传文件的功能,不胜感激,谢谢文件发送端代码:
/// <summary>
/// 发送
/// </summary>
private void SendFile()
{
if(this.FileName.Text.Trim() == "" )
{
this.labTestTrans.Text = "请选择需要传输的文件!";
return;
}
else
if(this.hostName.Text.Trim() == "" )
{
this.labTestTrans.Text = "请输入远程主机名!";
return;
}
else
if(this.portCode.Text.Trim() == "")
{
this.labTestTrans.Text = "请输入远程主机端口号";
return;
}
this.labTestTrans.Text = "正在与远程主机建立连接…";
try
{
string SendFileName=this.FileName.Text.Trim(); //取得预发送的文件名
string RemoteHostName=this.hostName.Text.Trim(); //远程主机
int RemotePort=Int32.Parse(this.portCode.Text.Trim());//远程端口
IPHostEntry ipInfo=Dns.GetHostByName(RemoteHostName); //得到主机信息
IPAddress RemoteIp=ipInfo.AddressList[0]; //取得IPAddress[]/得到远程接收IP
TcpClient client = new TcpClient();
client.Connect(RemoteIp, RemotePort);
this.labTestTrans.Text = "已与远程主机:"+RemoteHostName+":"+RemotePort+" 建立连接!";
NetworkStream clientStream = client.GetStream();//创建接收用的Stream
//读取源文件至字节数组
FileStream fs = new FileStream(SendFileName, FileMode.Open, FileAccess.Read);
BinaryReader fileReader = new BinaryReader(fs,Encoding.UTF8);
long FileLength = fs.Length;//文件长度
int hasRead = 0;
do
{ arrbyte = new byte[4096];
hasRead = fileReader.Read(arrbyte,0,arrbyte.Length);
clientStream.Write(arrbyte, 0, hasRead);
}while(hasRead > 0);
clientStream.Close();
client.Close();
}
catch ( Exception se)
{
MessageBox.Show ( se.Message , "错误" ) ;
}
}
文件接收端代码:
private void Receive()
{
try
{
//获取本机主机名
IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());
IPAddress LocalIP = ieh.AddressList[0];
int LocalPort=Int32.Parse(this.LocalPort.Text);
//新建监听
listener = new TcpListener(LocalIP, LocalPort);
listener.Stop();//关闭先前监听计划
listener.Start();//开始监听
this.ReceiveLabel.Text = "程序正在监听..." ;
while (true)
{
const int bufferSize = 4096;
TcpClient client = listener.AcceptTcpClient();
//接收客户端传过来的数据
NetworkStream clientStream = client.GetStream();
byte[] responseBuffer = new byte[bufferSize];
MemoryStream memStream = new MemoryStream();
string SaveName = this.ReceiveName.Text;
StreamReader reader = new StreamReader(memStream);
int bytesRead = 0;
FileStream fs ;
do
{
bytesRead = clientStream.Read(responseBuffer, 0, bufferSize);
memStream.Write(responseBuffer, 0, bytesRead);
}while (bytesRead > 0);
fs = new FileStream(SaveName, FileMode.OpenOrCreate);
BinaryWriter w = new BinaryWriter(fs);
w.Write(memStream.ToArray());
fs.Close();
this.RecMessage.Text = "文件接收成功!\n\r完成时间:"+System.DateTime.Now.ToString()+"\n\r文件名:"+SaveName;
}
}
catch ( System.Security.SecurityException )
{
MessageBox.Show ( "侦听失败!" , "错误" ) ;
}
}