• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
三人行者,必有我师焉
为了自己的理想,我愿意付出全部的力量
博客园    首页    新随笔    联系   管理    订阅  订阅

c# 文件传输

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

send :

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

Code

receive:

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

 

 

 

posted @ 2008-10-14 00:25  wsy6634  阅读(6061)  评论(3)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3