C#实现的Ftp 文件上传与下载类

发布时间:2020-09-02编辑:脚本学堂
本文介绍下,用C# .net实现的一个ftp文件上传与下载的类,有需要的朋友,可以参考学习下。

1,ftp上传与下载类:
 

复制代码 代码示例:

using System;
using System.IO;
using System.Net;
namespace WindowsFormsApplication1
{
    public class FtpOption
    {
        #region

        string serverIP;
        string serverPort;
        string userId;
        string passWord;

        public FtpOption(string serverIP, string serverPort, string userId, string passWord)
        {
            this.serverIP = serverIP;
            this.serverPort = serverPort ?? "21";
            this.userId = userId;
            this.passWord = passWord;
        }

        private FtpWebRequest OpenRequest(Uri uri, string ftpMethord)
        {
            try
            {
                FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
                ftpRequest.Credentials = new NetworkCredential(userId, passWord);
                ftpRequest.Method = ftpMethord;
                ftpRequest.UseBinary = true;
                return ftpRequest;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private FtpWebResponse OpenResponse(Uri uri, string ftpMethord)
        {
            try
            {
                return this.OpenRequest(uri, ftpMethord).GetResponse() as FtpWebResponse;
            }
            catch
            {
                throw new Exception("登录到Ftp服务器失败!");
            }
        }

        #endregion

        /// <summary>
        /// 下载(重命名)
        /// </summary>
        /// <param name="sourceFullPath">下载文件全路径</param>
        /// <param name="targetFullPath">下载到本机全路径(包含文件名)</param>
        /// <returns></returns>
        public bool DownLoadReName(string sourceFullPath, string targetFullPath)
        {
            try
            {
                Uri uri = new Uri(string.Format("ftp://{0}/{1}", serverIP, sourceFullPath));
                FtpWebResponse downloadResponse = OpenResponse(uri, WebRequestMethods.Ftp.DownloadFile);
                Stream responseStream = downloadResponse.GetResponseStream();
                FileStream fileStream = File.Create(targetFullPath);
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while (true)
                {
                    bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                        break;
                    fileStream.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();
                responseStream.Close();
                return true;
            }
            catch
            {
                throw new Exception("获取下载文件失败!");
            }
        }
        /// <summary>
        /// 下载(按原名直接)
        /// </summary> www.jb200.com
        /// <param name="loadFullPath">下载文件的全路径</param>
        /// <param name="targePath">下载到指定的地址(E:/)</param>
        /// <returns></returns>
        public bool DownLoadNotReName(string sourceFullPath, string targePath)
        {
            try
            {
                string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("/"));
                return DownLoadReName(sourceFullPath, targePath + fileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="sourceFullPath">要上传文件的地址(G:/Ftp.txt)</param>
        /// <param name="targetPath">服务器端地址(temp)</param>
        /// <returns></returns>
        public bool UploadFile(string sourceFullPath, string targetPath)
        {
            try
            {
                string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("/") + 1);
                //检查路径
                Uri uri = new Uri(string.Format("ftp://{0}:{1}/{2}/{3}", serverIP, serverPort, targetPath, fileName));
                FtpWebRequest request = this.OpenRequest(uri, WebRequestMethods.Ftp.UploadFile);
                Stream requestStream = request.GetRequestStream();
                FileStream fileStream = new System.IO.FileStream(sourceFullPath, FileMode.Open);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while (true)
                {
                    bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                        break;
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Close();
                request.GetResponse();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}

2,调用示例
 

复制代码 代码示例:

//调用:
FtpOption ftp = new FtpOption("10.XXX.3.90", "21", "uid", "pwd");

//下载文件:
bool success = ftp.DownLoadNotReName("file/201305/2013k4032.gif", "E:/");
bool success = ftp.DownLoadReName("file/201306/2044323o4j53.jpg", "E:/rename.003");

//上传文件:
bool success=ftp.UploadFile("G:/Ftp.txt","temp");