c# 文件传输

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

send :

ContractedBlock.gif ExpandedBlockStart.gif Code
  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, 04098)) != 0)                 //这个注意是将文件写成流的形式
            {
                client.Client.Send(b,data,SocketFlags.None);           
//发送文件流到目标机器
            }
           client.Client.Shutdown(SocketShutdown.Both);
           binaryreader.Close();
           file.Close();

ContractedBlock.gifCode

receive:

ContractedBlock.gif ExpandedBlockStart.gif Code
 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(
"文件传输完毕");

 

 

 

转载于:https://www.cnblogs.com/wsy6634/archive/2008/10/14/1310449.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值