C#文件传输

今天终于把文件传输问题给研究明白了,特发此代码用来帮助正在学习的人们。

发送代码:

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();

接收代码:

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(“文件传输完毕”);

}

来源URL:http://lovelvshuang.blog.163.com/blog/static/1369117520097201551228/