码迷,mamicode.com
首页 > Windows程序 > 详细

C#实现FTP上传下载程序

时间:2020-11-30 16:01:19      阅读:17      评论:0      收藏:0      [点我收藏+]

标签:tostring   hub   write   ssl   close   event   cep   collect   offset   

本文是利用C# 实现FTP上传下载的小例子,以供学习分享使用。

涉及知识点:

  FtpWebRequest【实现文件传输协议 (FTP) 客户端】 / FtpWebResponse【封装文件传输协议 (FTP) 服务器对请求的响应】Ftp的操作。

效果图如下

技术图片

 

 技术图片

 

 技术图片

 

 核心代码如下

技术图片
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.IO;
using System.Threading;

namespace 上传下载程序
{
    
    public partial class Form1 : Form
    {
        private static readonly string rootPath = "/";
        private static readonly int defaultReadWriteTimeout = 300000;
        private static readonly int defaultFtpPort = 21;
        

        #region 设置初始化参数
        private string host = string.Empty;
        public string Host
        {
            get
            {
                return this.host ?? string.Empty;
            }
        }

        private string username = string.Empty;
        public string Username
        {
            get
            {
                return this.username;
            }
        }

        private string password = string.Empty;
        public string Password
        {
            get
            {
                return this.password;
            }
        }

        IWebProxy proxy = null;
        public IWebProxy Proxy
        {
            get
            {
                return this.proxy;
            }
            set
            {
                this.proxy = value;
            }
        }

        private int port = defaultFtpPort;
        public int Port
        {
            get
            {
                return port;
            }
            set
            {
                this.port = value;
            }
        }

        private bool enableSsl = false;
        public bool EnableSsl
        {
            get
            {
                return enableSsl;
            }
        }

        private bool usePassive = true;
        public bool UsePassive
        {
            get
            {
                return usePassive;
            }
            set
            {
                this.usePassive = value;
            }
        }

        private bool useBinary = true;
        public bool UserBinary
        {
            get
            {
                return useBinary;
            }
            set
            {
                this.useBinary = value;
            }
        }

        private string remotePath = rootPath;
        public string RemotePath
        {
            get
            {
                return remotePath;
            }
            set
            {
                string result = rootPath;
                if (!string.IsNullOrEmpty(value) && value != rootPath)
                {
                    result = Path.Combine(Path.Combine(rootPath, value.TrimStart(/).TrimEnd(/)), "/"); // 进行路径的拼接
                }
                this.remotePath = result;
            }
        }

        private int readWriteTimeout = defaultReadWriteTimeout;
        public int ReadWriteTimeout
        {
            get
            {
                return readWriteTimeout;
            }
            set
            {
                this.readWriteTimeout = value;
            }
        }
        #endregion

        #region 构造函数

//       public FtpHelper(string host, string username, string password)
//            : this(host, username, password, defaultFtpPort, null, false, true, true, defaultReadWriteTimeout)
//        {
//       }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="host">主机名</param>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="port">端口号 默认21</param>
        /// <param name="proxy">代理 默认没有</param>
        /// <param name="enableSsl">是否使用ssl 默认不用</param>
        /// <param name="useBinary">使用二进制</param>
        /// <param name="usePassive">获取或设置客户端应用程序的数据传输过程的行为</param>
        /// <param name="readWriteTimeout">读写超时时间 默认5min</param>
        public void FtpHelper(string host, string username, string password, int port, IWebProxy proxy, bool enableSsl, bool useBinary, bool usePassive, int readWriteTimeout)
        {
            this.host = host.ToLower().StartsWith("ftp://") ? host : "ftp://" + host;
            this.username = username;
            this.password = password;
            this.port = port;
            this.proxy = proxy;
            this.enableSsl = enableSsl;
            this.useBinary = useBinary;
            this.usePassive = usePassive;
            this.readWriteTimeout = readWriteTimeout;
        }
        #endregion

        /// <summary>
        /// 拼接URL
        /// </summary>
        /// <param name="host">主机名</param>
        /// <param name="remotePath">地址</param>
        /// <param name="fileName">文件名</param>
        /// <returns>返回完整的URL</returns>
        private string UrlCombine(string host, string remotePath, string fileName)
        {
            string result = new Uri(new Uri(new Uri(host.TrimEnd(/)), remotePath), fileName).ToString(); ;
            return result;
        }

        /// <summary>
        /// 创建连接
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="method">方法</param>
        /// <returns>返回 request对象</returns>
        private FtpWebRequest CreateConnection(string url, string method)
        {
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
            request.Credentials = new NetworkCredential(this.username, this.password);
            request.Proxy = this.proxy;
            request.KeepAlive = false;
            request.UseBinary = useBinary;
            request.UsePassive = usePassive;
            request.EnableSsl = enableSsl;
            request.Method = method;
            Console.WriteLine(request);
            return request;
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string str1 = textBox3.Text;
            string str2 = textBox4.Text;
            string str3 = textBox5.Text;
            FtpHelper(str1, str2, str3, defaultFtpPort, null, false, true, true, defaultReadWriteTimeout);
            string stradress = textBox1.Text;//上传文本地址
            FileInfo fileInfo = new FileInfo(stradress);
            FileInfo localFile = fileInfo;
            string remoteFileName = textBox2.Text;
            //bool result = false;
            if (localFile.Exists)
            {
                try
                {
                    string url = UrlCombine(Host, RemotePath, remoteFileName);
                    FtpWebRequest request = CreateConnection(url, WebRequestMethods.Ftp.UploadFile);

                    using (Stream rs = request.GetRequestStream())
                    using (FileStream fs = localFile.OpenRead())
                    {
                        byte[] buffer = new byte[1024 * 4];
                        int count = fs.Read(buffer, 0, buffer.Length);
                        while (count > 0)
                        {
                            rs.Write(buffer, 0, count);
                            count = fs.Read(buffer, 0, buffer.Length);
                        }
                        fs.Close();
                        //result = true;
                    }
                    label3.Text = "上传成功!";
                }
                catch (WebException ex)
                {
                     MessageBox.Show(ex.Message);
                }
                //return result;
            }
            // 处理本地文件不存在的情况
            //return false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string str1 = textBox3.Text;
            string str2 = textBox4.Text;
            string str3 = textBox5.Text;
            FtpHelper(str1, str2, str3, defaultFtpPort, null, false, true, true, defaultReadWriteTimeout);
            string localName = textBox1.Text; 
            string stradress = textBox2.Text;
            //FileInfo fileInfo = new FileInfo(stradress);
            string serverName = stradress;
           
            // bool result = false;
            using (FileStream fs = new FileStream(localName, FileMode.OpenOrCreate))
            {
                try
                {
                    string url = UrlCombine(Host, RemotePath,serverName);
                    Console.WriteLine(url);

                    FtpWebRequest request = CreateConnection(url, WebRequestMethods.Ftp.DownloadFile);
                    request.ContentOffset = fs.Length;
                    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                    {
                        fs.Position = fs.Length;
                        byte[] buffer = new byte[1024 * 4];
                        int count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
                        while (count > 0)
                        {
                            fs.Write(buffer, 0, count);
                            count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
                        }
                        response.GetResponseStream().Close();
                    }
                    //result = true;
                    label3.Text = "下载成功!";
                }
                catch (WebException ex)
                {
                    // 处理ftp连接中的异常
                   // MessageBox.Show(ex.Message);
                }
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
View Code

--------------------------------------------------------------------------------------------------------------------------

技术图片

 

--------------------------------------------------------------------------------------------------------------------------

 源码见github

C#实现FTP上传下载程序

标签:tostring   hub   write   ssl   close   event   cep   collect   offset   

原文地址:https://www.cnblogs.com/DWVictor/p/14036305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!