Send:
代码
string path = "E:\\c#\\convey_file\\convey_file\\Form1.cs"; //要传输的文件
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("192.168.0.52"),9999);
FileStream file = new FileStream(path,FileMode.Open,FileAccess.Read); //注意与receive的filestream的区别
BinaryReader binaryreader = new BinaryReader(file);
byte[] b = new byte[4098];
int data;
Console.WriteLine("正在发送文件");
while ((data = binaryreader.Read(b, 0, 4098)) != 0) //这个注意是将文件写成流的形式
{
client.Client.Send(b,data,SocketFlags.None); //发送文件流到目标机器
}
client.Client.Shutdown(SocketShutdown.Both);
binaryreader.Close();
file.Close();
Receive:
代码
private Socket s;
TcpListener tl;
public void lis()
{
string path = "d:\\1.cs"; //要传入文件的路径
tl = new TcpListener(9999);
tl.Start();
Console.WriteLine("等待接受");
s = tl.AcceptSocket();
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); //注意这个的属性和send端有所不同
BinaryWriter binarywrite = new BinaryWriter(fs);
int count;
byte[] b = new byte[4098];
while ((count = s.Receive(b, 4098, SocketFlags.None)) != 0) //这个是接受文件流
{
binarywrite.Write(b,0,count); //将接收的流用写成文件
}
binarywrite.Close();
fs.Close();
s.Close();
tl.Stop();
Console.WriteLine("文件传输完毕");
转载自:http://www.cnblogs.com/wsy6634/archive/2008/10/14/1310449.html