在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#网络编程 → FTP文件传输(入门级示例)

FTP文件传输(入门级示例)

C#网络编程

下载此实例
  • 开发语言:C#
  • 实例大小:0.14M
  • 下载次数:34
  • 浏览次数:523
  • 发布时间:2018-12-27
  • 实例类别:C#网络编程
  • 发 布 人:子欲养树欲静
  • 文件格式:.zip
  • 所需积分:5
 相关标签: FTP

实例介绍

【实例简介】


采用FTP PASV模式设计一个FTP服务器程序和一个FTP客户机程序,具有文件夹内容浏览和文件下载功能,服务器程序能够接收多个客户机的FTP请求并且能够对客户机身份进行验证。


【实例截图】



from clipboard


from clipboard 

【核心代码】

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

using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

using System.Collections;
using System.Net.NetworkInformation;


namespace client
{
   

    public partial class Form1 : Form
    {
        TcpClient controltc;
        NetworkStream controlns;
        StreamReader controlsr;
        StreamWriter controlsw;



        private static string ext =null;


        public Form1()
        {
            InitializeComponent();
            this.buttonUpDir.Enabled= false;

            Control.CheckForIllegalCrossThreadCalls = false;
        }

        
        private void closecontrolconnection()
        {
            this.controltc.Close();
            this.controlns.Close();
            this.controlsr.Close();
            this.controlsw.Close();
        }
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            try
            {
            
                controltc = new TcpClient("192.168.1.6", 21);
            }
            catch (Exception ee)
            {
                MessageBox.Show("与服务器连接失败!"   ee.ToString());
                return;
            }
            controlns = controltc.GetStream();
            controlsr = new StreamReader(controlns, System.Text.Encoding.Unicode);
            controlsw = new StreamWriter(controlns, System.Text.Encoding.Unicode);

            string str = controlsr.ReadLine();
            this.listBoxInfo.Items.Add("收到:"   str);

            controlsw.WriteLine("USER ftpuser");
            controlsw.Flush();
            str = controlsr.ReadLine();


            this.listBoxInfo.Items.Add("收到" str);
            if (str == "421")
            {
                MessageBox.Show("用户名不正确");
                this.closecontrolconnection();
                return;
            }

            controlsw.WriteLine("PASS ftppass");
            controlsw.Flush();
            str = controlsr.ReadLine();
            this.listBoxInfo.Items.Add("收到:"   str);
            if (str == "421")
            {
                MessageBox.Show("密码不正确");
                this.closecontrolconnection();
                return;
            }

          //获取FTP根目录下的子目录和文件列表
            GetDirAndFiles(@"server:\");
        }
        private void button1_Click(object sender, EventArgs e)
        {
           
        }
        private void GetDirAndFiles(string path)
        {
            this.groupBoxDir.Text = path;
            //-------判断当前目录是否为虚拟根目录---------
            if (path == @"server:\")
            {
                this.buttonUpDir.Enabled = false;
            }
            else
            {
                this.buttonUpDir.Enabled = true;
            }

            TcpClient datatc = this.getdataconnection();
            NetworkStream datans = datatc.GetStream();
            StreamReader datasr = new StreamReader(datans);



            //获取目录和文件列表
            controlsw.WriteLine("LIST "   path);
            controlsw.Flush();
            this.listBoxInfo.Items.Add("发送:LIST "   path);
            this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;
            string str = controlsr.ReadLine();

            this.listBoxInfo.Items.Add("收到:"   str);
            this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;
            if (str == "125")  //表示服务器已经准备好数据,并开始传送
            {
                //获取子目录列表
                this.listBoxDir.Items.Clear();
                str = datasr.ReadLine();
                this.listBoxInfo.Items.Add("收到:"   str);
                this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;
                string[] strarray;
                  //字符串长度为0,说明当前目录下没有子目录
                if (str.Length > 0)
                {
                    strarray = str.Split('@');
                    for (int i = 0; i < strarray.Length; i  )
                    {
                        this.listBoxDir.Items.Add(strarray[i]   "\\");
                    }
                }
                //获取文件列表
                this.listBoxFile.Items.Clear();
                str = datasr.ReadLine();
                this.listBoxInfo.Items.Add("收到:"   str);
                this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;
                //字符串长度为0,说明当前目录下没有文件
                if (str.Length > 0)
                {
                    strarray = str.Split('@');
                    for (int i = 0; i < strarray.Length; i  )
                    {
                        this.listBoxFile.Items.Add(strarray[i]);
                    }
                }

                datasr.Close();
                datans.Close();
                datatc.Close();

                this.buttonDownload.Enabled = false;

                str = controlsr.ReadLine();
                this.listBoxInfo.Items.Add("收到:"   str);
                this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;
            }
        }
        private TcpClient  getdataconnection()
        {
            controlsw.WriteLine("PASV ");
            controlsw.Flush();
            string str = controlsr.ReadLine();
            if (str != "227")
            {
                MessageBox.Show("FTP被动模式失败!");
            }
            str = controlsr.ReadLine();
            int rdp = int.Parse(str.Substring(str.IndexOf(" ")  1));
            TcpClient datatc = new TcpClient("127.0.0.1",rdp);
            controlsw.WriteLine("150");
            controlsw.Flush();
            return datatc;
        }

        private void buttonUpDir_Click(object sender, EventArgs e)
        {
            string path = this.groupBoxDir.Text;
            path = path.Substring(0,path.LastIndexOf("\\"));
            int num = path.LastIndexOf("\\");
            path = path.Substring(0, num   1);
            GetDirAndFiles(path);
        }

        private void buttonDisConnect_Click(object sender, EventArgs e)
        {
            controlsw.WriteLine("QUIT");
            controlsw.Flush();

            this.listBoxInfo.Items.Add("发送:QUIT");
            string str = controlsr.ReadLine();
            this.listBoxInfo.Items.Add("收到:" str);
            this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;
            controltc.Close();
        }

        private void listBoxDir_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBoxDir.SelectedIndex == -1)
            {
                GetDirAndFiles(this.groupBoxDir.Text);
            }
            else
            {
                GetDirAndFiles(this.listBoxDir.SelectedItem.ToString());
            }
        }

        private void listBoxFile_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBoxFile.SelectedIndex == -1)
            {
                this.buttonDownload.Enabled = false;
            }
            else
            {
                this.buttonDownload.Enabled = true;
            }
        }
        private string getfileext(string filename)
        {
            try
            {
                char[] point = new char[] { ',' };
                string[] filename2 = filename.Split(point);
                return filename2[1];
            }
            catch
            {
                return null;
            }
        }

        private void buttonDownload_Click(object sender, EventArgs e)
        {
            ext = getfileext(this.listBoxFile.Text);
            SaveFileDialog myfile = new SaveFileDialog();
            myfile.Filter = ext   " files"   "(*."   ext   ")|*."   ext   "|All files (*.*)|*.*";
            

            if (myfile.ShowDialog() == DialogResult.OK)
            {
                //重画窗体内的所有控件,使窗体显示完整
                foreach (Control control in this.Controls)
                {
                    control.Update();
                }

                TcpClient datatc = this.getdataconnection();
                NetworkStream datans = datatc.GetStream();
                StreamReader datasr = new StreamReader(datans);

                string path = this.listBoxFile.SelectedItem.ToString();

                controlsw.WriteLine("RETR "   path);
                controlsw.Flush();


                this.listBoxInfo.Items.Add("发送:RETR "   path);
                this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;
                string str = controlsr.ReadLine();


                this.listBoxInfo.Items.Add("收到:"   str);
                this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;
                if (str == "125")  //表示服务器文件状态良好
                {
                    string str1 = datasr.ReadLine();
                    this.listBoxInfo.Items.Add("文件长度:"   str1   "字节");
                    this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;
               
                   
                    this.lbdf.Text="正在下载``````";
                    FileStream fs = new FileStream(myfile.FileName, FileMode.Create, FileAccess.Write);
                    byte[] byteF = TransData.ReceiveVarData(datatc.Client);

                    if (byteF.Length == 0)
                    {
                        MessageBox.Show("??!!");
                    }


                    fs.Write(byteF,0,byteF.Length);
                    fs.Flush();
                    fs.Close();

                    datasr.Close();
                    datans.Close();
                    datatc.Close();

                    MessageBox.Show("下载完毕!");
                    this.lbdf.Text = "";

                    str = controlsr.ReadLine();
                    this.listBoxInfo.Items.Add("收到:" str);
                    this.listBoxInfo.SelectedIndex = this.listBoxInfo.Items.Count - 1;              
                }
            }
        }
    }
}

标签: FTP

网友评论

第 1 楼 longguanyao 发表于: 2019-06-19 11:58 43
怎么不通啊?

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有1条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警