c# winform Tcp文件传输例子

在这里插入图片描述

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TcpFile
{
    class DirectoryList
    {
        /*利用静态数据来存储文件路径列表*/
        private static ArrayList directorysList = new ArrayList();//存储目录列表数据

        public static ArrayList DirectorysList
        {
            get { return DirectoryList.directorysList; }
            set { DirectoryList.directorysList = value; }
        }
        private static ArrayList fileList = new ArrayList();//存储文件路径列表

        public static ArrayList FileList
        {
            get { return DirectoryList.fileList; }
            set { DirectoryList.fileList = value; }
        }
        public static void GetDirectory(string sourcePath)
        {
            if (Directory.Exists(sourcePath))//判断源文件夹是否存在
            {
                string[] tmp = Directory.GetFileSystemEntries(sourcePath);//获取源文件夹中的目录及文件路径,存入字符串
                //循环遍历
                for (int i = 0; i < tmp.Length; i++)
                {
                    if (File.Exists(tmp[i]))//如果是文件则存入FileList
                    {
                        FileList.Add(tmp[i]);
                    }
                    else
                    {
                        if ((Directory.GetDirectories(tmp[i])).Length == 0)//如果是最后一层目录则把其路径存入DirectorysList
                        {
                            DirectorysList.Add(tmp[i]);
                        }
                    }
                    //递归开始.......
                    GetDirectory(tmp[i]);
                }
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TcpFile
{
    /// <summary>
    /// 文件接收类
    /// </summary>
    class FileRecive
    {

        private TcpListener server;
        private Form1 fm;
        private NetworkStream stream;
        string ip;
        mFolderBrowserDialog _mFolderBrowserDialog;
        public FileRecive(Form1 fm  ,string _ip,int _port,mFolderBrowserDialog _mFolderBrowserDialog)
        {
            this.fm = fm;
            try
            {
                this.ip = _ip;
                this._mFolderBrowserDialog = _mFolderBrowserDialog;
                //this.server = new TcpListener(IPAddress.Parse(IpUtil.GetLocalIp()), IpUtil.GetRandomPort());
                this.server = new TcpListener(IPAddress.Parse(_ip), _port);

                server.Start();
            }
            catch (Exception e)
            {

                fm.Tip(e.Message);

            }
        }

        public void CloseServer()
        {
            server.Stop();
        }
        /// <summary>
        /// 接收文件
        /// </summary>
        public void run()
        {
           
            while (true)
            {

                try
                {
                    TcpClient client = null;
                    try
                    {
                        client = server.AcceptTcpClient();
                    }
                    catch (Exception)
                    {

                      
                    }
                  
                    if (client!=null&& client.Connected)
                    {
                        this.stream = client.GetStream();
                        byte[] msgs = new byte[1024];

                        int len = this.stream.Read(msgs, 0, msgs.Length);

                        string msg = Encoding.UTF8.GetString(msgs, 0, len);
                      
                        string[] tip = msg.Split('|');
                        //if (DialogResult.Yes == MessageBox.Show(ip + "给您发了一个文件:" + tip[0] + "大小为:" + (long.Parse(tip[2]) / 1024) + "kb ,确定要接收吗?", "接收提醒", MessageBoxButtons.YesNo))
                        //{

                            //将接收信息反馈给发送方
                            msg = "1";
                            msgs = Encoding.UTF8.GetBytes(msg);
                            this.stream.Write(msgs, 0, msgs.Length);
                            this.stream.Flush();
                            fm.SetState("正在接收:");
                        //开始接收文件
                        string path = null;
                        string dir = "";
                        if (tip[3] == fileType.File.ToString())
                        {
                            path = this._mFolderBrowserDialog.GetSavePath() + tip[0];
                        }
                        else if (tip[3] == fileType.dir.ToString())
                        {
                            path = this._mFolderBrowserDialog.GetSavePath() + tip[1].Substring(tip[1].IndexOf(":") + 2);//接收文件的存储路径

                        }else
                        {

                           
                        }
                        dir = Path.GetDirectoryName(path);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }


                        FileStream os = new FileStream(path, FileMode.OpenOrCreate);

                            byte[] data = new byte[1024];
                            long currentprogress = 0;
                            int length = 0;
                            fm.UpDateProgress((int)currentprogress);
                            fm.UpdateCurrentFileName(path);
                        if (client == null||!client.Connected||!stream.CanRead)
                        {
                            fm.Tip("不能读取");
                        }
                        while (client.Connected&&stream.CanRead&&(length = this.stream.Read(data, 0, data.Length)) > 0)
                            {
                                currentprogress += length;
                                //更新进度条
                                fm.UpDateProgress((int)(currentprogress * 100 / long.Parse(tip[2])));
                                os.Write(data, 0, length);
                            }
                            os.Flush();
                            this.stream.Flush();
                            os.Close();
                            this.stream.Close();
                           // fm.Tip("成功接收文件并存入了" + path + "中!");
                            
                           //  fm.Exit();

                        //}
                   
                    }

                }
                catch (Exception e)
                {
                    fm.Tip(e.Message);

                }
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TcpFile
{
    class FileSend
    {
        private TcpClient client;
        private NetworkStream stream;
        private string[] param;
        private Form1 fm;
        public FileSend(Form1 fm, params string[] param)
        {

            this.param = param;
            this.fm = fm;
        }

        public void Send()
        {
            try
            {
                //连接接收端
                this.client = new TcpClient(param[0], int.Parse(param[1]));
                string msg = param[2] + "|"+param[3] + "|" + param[4]+"|" + param[5];
                byte[] m = Encoding.UTF8.GetBytes(msg);

                while (true)
                {
                    try
                    { 

                        this.stream = this.client.GetStream();
                        this.stream.Write(m, 0, m.Length);
                        this.stream.Flush();
                        byte[] data = new byte[1024];
                        int len = this.stream.Read(data, 0, data.Length);
                        msg = Encoding.UTF8.GetString(data, 0, len);
                        //对方要接收我发送的文件
                        if (msg.Equals("1"))
                        {
                            fm.SetState("正在发送:");
                            FileStream os = new FileStream(param[3], FileMode.OpenOrCreate);

                            data = new byte[1024];
                            //记录当前发送进度
                            long currentprogress = 0;
                            len = 0;
                            //每个数据进度条清零
                            fm.UpDateProgress((int)currentprogress);
                            fm.UpdateCurrentFileName(param[3]);
                            while ((len = os.Read(data, 0, data.Length)) > 0)
                            {
                                currentprogress += len;
                                //更新进度条
                                fm.UpDateProgress((int)(currentprogress * 100 / long.Parse(param[4])));
                                this.stream.Write(data, 0, len);
                            }
                            Thread.Sleep(1000);
                            os.Flush();
                            this.stream.Flush();
                            os.Close();
                            this.stream.Close();
                            client.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        return;
                    }
                    
                }
               
            }
            catch (Exception e)
            {

                fm.Tip(e.Message);

            }

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace TcpFile
{


    class IpUtil
    {
        /// <summary>
        /// 获取本地IP的方法IPV4
        /// </summary>
        /// <returns></returns>
        public static string GetIPAddress()
        {

            //获取本地所有IP地址
            IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress[] ip = ipe.AddressList;
            for (int i = 0; i < ip.Length; i++)
            {
                if (ip[i].AddressFamily.ToString().Equals("InterNetwork"))
                {

                    return ip[i].ToString();
                }
            }
            return null;
        }
        /// <summary>
        /// 获取本地IP的方法IPV6
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIp()
        {
            IPHostEntry localhost = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress localaddr = localhost.AddressList[0];
            return localaddr.ToString();
        }
        /// <summary>
        /// 产生随机端口
        /// </summary>
        /// <returns></returns>
        public static int GetRandomPort()
        {
            return new Random().Next(1000) + 5000;
        }
    }
}

namespace TcpFile
{
    public enum fileType
    { 
    File,
    dir,
    none
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TcpFile
{
    class mFolderBrowserDialog
    {
        Form1 fm;
        private string Savepath;
        private string SendPath;

        /// <summary>
        /// 文件名
        /// </summary>
        private string fileName;
        /// <summary>
        /// 文件路径
        /// </summary>
        private string filePath;
        /// <summary>
        /// 文件大小
        /// </summary>
        private long fileSize;
        public mFolderBrowserDialog(Form1 fm)
        {
            this.fm = fm;
        }


        public void SetSavePath()
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择接收文件的路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                Savepath = dialog.SelectedPath + "\\";
                fm.UpdateText();
            }
        }
        public string GetSavePath()
        {
            return Savepath;
        }

        public void SetSendPath()
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                SendPath = dialog.SelectedPath + "\\";
            }
        }
        public string GetSendPath()
        {
            return SendPath;
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void SelectFile()
        {

            OpenFileDialog dig = new OpenFileDialog();

            dig.ShowDialog();

            //获取文件名
            this.fileName = dig.SafeFileName;

            //获取文件路径
            this.filePath = dig.FileName;
            if (filePath != null && filePath.Length != 0)
            {
                FileInfo f = new FileInfo(this.filePath);
                //获取文件大小
                this.fileSize = f.Length;
            }

        }

        public string GetSelectfileName()
        {
            return fileName;
        }
        public string GetSelectfilePath()
        {
            return filePath;
        }
        public long GetSelectfileSize()
        {
            return fileSize;
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TcpFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            LocalIPAdress = IpUtil.GetIPAddress();
            Netport = IpUtil.GetRandomPort();
            selfIPText.Text = LocalIPAdress;
            selfPortText.Text = Netport.ToString();
            IPtext.Text = LocalIPAdress;
            UpDateProgress(0);
            _mFolderBrowserDialog = new mFolderBrowserDialog(this);
            this.FormClosed += FrmMain_FormClosing;

        }

        private void FrmMain_FormClosing(object sender, FormClosedEventArgs e)
        {
            
        }

        bool serverStared = false;
        FileRecive s;
        private void StartRecieve_Click(object sender, EventArgs e)
        {
            string SavePath = _mFolderBrowserDialog.GetSavePath();
            if (SavePath == null||SavePath.Length ==0)
            {
                Tip("请选选择接收文件存储路径");
                return;
            }
            Thread.CurrentThread.IsBackground = true;
           
            Thread StartThread = null;
            if (serverStared == false)
            {
                try
                {
                    s = new FileRecive(this, LocalIPAdress, Netport, _mFolderBrowserDialog);
                    StartThread =  new Thread(s.run);
                    StartThread.Start();
                    StartRecieve.Text = "服务器已开启";
                    serverStared = true;
                }
                catch (Exception)
                {

                    throw;
                }
            }
            else {
                s.CloseServer();
                serverStared = false;
                StartRecieve.Text = "开启服务器";
                UpDateProgress(0);
                try
                {
                    StartThread.Abort();
                }
                catch (Exception)
                {
                }
                StartThread = null;
            }
           
        }
        private void SelectFilePathbtn_Click(object sender, EventArgs e)
        {
            _mFolderBrowserDialog. SelectFile();
            SelectedFilePathText.Text = _mFolderBrowserDialog.GetSelectfilePath();
            IsFile = true;
        }
        private void selectDirPathbtn_Click(object sender, EventArgs e)
        {
            _mFolderBrowserDialog.SetSendPath();
            selectDirPathText.Text = _mFolderBrowserDialog.GetSendPath();
            DirectoryList.GetDirectory(_mFolderBrowserDialog.GetSendPath());
            IsFile = false;
        }

        private void Sendbtn_Click(object sender, EventArgs e)
        {
            if (selectDirPathText.Text != null && selectDirPathText.Text.Length != 0 && !IsFile)
            {
                SendAllFile();

            }
            else if (SelectedFilePathText.Text != null && SelectedFilePathText.Text.Length != 0 && IsFile)
            {
                SendFile();
            }
            else {
                Tip("其他");
            }
          
           
        }

        #region
       

        private string LocalIPAdress;
        private int Netport;
        private mFolderBrowserDialog _mFolderBrowserDialog;
        private bool IsFile = false;
        /// <summary>
        /// 信息提示框
        /// </summary>
        /// <param name="msg"></param>
        public void Tip(string msg)
        {
            MessageBox.Show(msg, "温馨提示");
        }
        // <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendFile()
        {
            string ip = IPtext.Text;
            string port = Porttext.Text;
           
            if (_mFolderBrowserDialog .GetSelectfileName()== null|| _mFolderBrowserDialog.GetSelectfileName().Length == 0)
            {

                Tip("请选择文件");
                return;
            }
            if (ip.Length == 0 || port.ToString().Length == 0)
            {

                Tip("端口和ip地址是必须的!");
                return;
            }
            var c = new FileSend(this, new string[] { ip, port, _mFolderBrowserDialog.GetSelectfileName(), _mFolderBrowserDialog.GetSelectfilePath(), _mFolderBrowserDialog.GetSelectfileSize().ToString(),fileType.File.ToString() });
            new Thread(c.Send).Start();
        }

        private void SendAllFile()
        {
            string ip = IPtext.Text;
            string port = Porttext.Text;

         
            if (ip.Length == 0 || port.ToString().Length == 0)
            {
                Tip("端口和ip地址是必须的!");
                return;
            }
            foreach (string item in DirectoryList.FileList)
            {
                FileInfo f = new FileInfo(item);
                var c = new FileSend(this, new string[] { ip, port, f.Name, item, f.Length.ToString(),fileType.dir.ToString() });
                new Thread(c.Send).Start();
            }
        }
       

        /// <summary>
        /// 更新进度条
        /// </summary>
        /// <param name="value"></param>
        public void UpDateProgress(int value)
        {
            Action<int> ShowMsg = Msg => {
                this.progressBar1.Value = Msg;
                this.numlable.Text = Msg + "%";
                Application.DoEvents();
            };
            this.Invoke(ShowMsg, value);
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="state"></param>
        public void SetState(string state)
        {
            Action<string> ShowMsg = Msg => {
                Currentlable.Text = Msg;
            };
            this.Invoke(ShowMsg, state);
            
        }
        /// <summary>
        /// 退出程序
        /// </summary>
        //public void Exit()
        //{
        //    Application.Exit();
        //}
        #endregion

        private void SavePathbtn_Click(object sender, EventArgs e)
        {
            _mFolderBrowserDialog.SetSavePath();
        }
        /// <summary>
        /// 更新文件存储路径的文本
        /// </summary>
        public void UpdateText()
        {
            SavePathtext.Text = _mFolderBrowserDialog.GetSavePath();
        }
        public void UpdateCurrentFileName(string _fileName)
        {
            Action<string> ShowMsg = Msg => {
                CurrentFileName.Text = "当前文件名字是 : " + Msg;
            };
            this.Invoke(ShowMsg, _fileName);
          
        }

      
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值