C# FTP上传下载 代码

2019PHP高薪工程师学习路线图....>>>

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    using System.Net;  
    using System.IO;  
      
    namespace JianKunKing.Common.Ftp  
    {  
        /// <summary>  
        /// ftp方式文件下载上传  
        /// </summary>  
        public static class FileUpDownload  
        {  
            #region 变量属性  
            /// <summary>  
            /// Ftp服务器ip  
            /// </summary>  
            public static string FtpServerIP = string.Empty;  
            /// <summary>  
            /// Ftp 指定用户名  
            /// </summary>  
            public static string FtpUserID = string.Empty;  
            /// <summary>  
            /// Ftp 指定用户密码  
            /// </summary>  
            public static string FtpPassword = string.Empty;  
     
            #endregion  
     
            #region 从FTP服务器下载文件,指定本地路径和本地文件名  
            /// <summary>  
            /// 从FTP服务器下载文件,指定本地路径和本地文件名  
            /// </summary>  
            /// <param name="remoteFileName">远程文件名</param>  
            /// <param name="localFileName">保存本地的文件名(包含路径)</param>  
            /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>  
            /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>  
            /// <returns>是否下载成功</returns>  
            public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action<int, int> updateProgress = null)  
            {  
                FtpWebRequest reqFTP, ftpsize;  
                Stream ftpStream = null;  
                FtpWebResponse response = null;  
                FileStream outputStream = null;  
                try  
                {  
                    outputStream = new FileStream(localFileName, FileMode.Create);  
                    if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)  
                    {  
                        throw new Exception("ftp下载目标服务器地址未设置!");  
                    }  
                    Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);  
                    ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);  
                    ftpsize.UseBinary = true;  
      
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);  
                    reqFTP.UseBinary = true;  
                    if (ifCredential)//使用用户身份认证  
                    {  
                        ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);  
                        reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);  
                    }  
                    ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;  
                    FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();  
                    long totalBytes = re.ContentLength;  
                    re.Close();  
      
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;  
                    response = (FtpWebResponse)reqFTP.GetResponse();  
                    ftpStream = response.GetResponseStream();  
      
                    //更新进度    
                    if (updateProgress != null)  
                    {  
                        updateProgress((int)totalBytes, 0);//更新进度条     
                    }  
                    long totalDownloadedByte = 0;  
                    int bufferSize = 2048;  
                    int readCount;  
                    byte[] buffer = new byte[bufferSize];  
                    readCount = ftpStream.Read(buffer, 0, bufferSize);  
                    while (readCount > 0)  
                    {  
                        totalDownloadedByte = readCount + totalDownloadedByte;  
                        outputStream.Write(buffer, 0, readCount);  
                        //更新进度    
                        if (updateProgress != null)  
                        {  
                            updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条     
                        }  
                        readCount = ftpStream.Read(buffer, 0, bufferSize);  
                    }  
                    ftpStream.Close();  
                    outputStream.Close();  
                    response.Close();  
                    return true;  
                }  
                catch (Exception)  
                {  
                    return false;  
                    throw;  
                }  
                finally  
                {  
                    if (ftpStream != null)  
                    {  
                        ftpStream.Close();  
                    }  
                    if (outputStream != null)  
                    {  
                        outputStream.Close();  
                    }  
                    if (response != null)  
                    {  
                        response.Close();  
                    }  
                }  
            }  
     
            #endregion  
     
            #region 上传文件到FTP服务器  
            /// <summary>  
            /// 上传文件到FTP服务器  
            /// </summary>  
            /// <param name="localFullPath">本地带有完整路径的文件名</param>  
            /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>  
            /// <returns>是否下载成功</returns>  
            public static bool FtpUploadFile(string localFullPath, Action<int, int> updateProgress = null)  
            {  
                FtpWebRequest reqFTP;  
                Stream stream = null;  
                FtpWebResponse response = null;  
                FileStream fs = null;  
                try  
                {  
                    FileInfo finfo = new FileInfo(localFullPath);  
                    if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)  
                    {  
                        throw new Exception("ftp上传目标服务器地址未设置!");  
                    }  
                    Uri uri = new Uri("ftp://" + FtpServerIP + "/" + finfo.Name);  
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);  
                    reqFTP.KeepAlive = false;  
                    reqFTP.UseBinary = true;  
                    reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);//用户,密码  
                    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//向服务器发出下载请求命令  
                    reqFTP.ContentLength = finfo.Length;//为request指定上传文件的大小  
                    response = reqFTP.GetResponse() as FtpWebResponse;  
                    reqFTP.ContentLength = finfo.Length;  
                    int buffLength = 1024;  
                    byte[] buff = new byte[buffLength];  
                    int contentLen;  
                    fs = finfo.OpenRead();  
                    stream = reqFTP.GetRequestStream();  
                    contentLen = fs.Read(buff, 0, buffLength);  
                    int allbye = (int)finfo.Length;  
                    //更新进度    
                    if (updateProgress != null)  
                    {  
                        updateProgress((int)allbye, 0);//更新进度条     
                    }  
                    int startbye = 0;  
                    while (contentLen != 0)  
                    {  
                        startbye = contentLen + startbye;  
                        stream.Write(buff, 0, contentLen);  
                        //更新进度    
                        if (updateProgress != null)  
                        {  
                            updateProgress((int)allbye, (int)startbye);//更新进度条     
                        }  
                        contentLen = fs.Read(buff, 0, buffLength);  
                    }  
                    stream.Close();  
                    fs.Close();  
                    response.Close();  
                    return true;  
      
                }  
                catch (Exception)  
                {  
                    return false;  
                    throw;                 
                }  
                finally  
                {  
                    if (fs != null)  
                    {  
                        fs.Close();  
                    }  
                    if (stream != null)  
                    {  
                        stream.Close();  
                    }  
                    if (response != null)  
                    {  
                        response.Close();  
                    }  
                }  
            }  
            #endregion   
      
        }  
    }  

调用实例:

下载(不需要带iis部分的路径):

    FileUpDownload.FtpServerIP = "192.168.1.1";  
               FileUpDownload.FtpUserID = "ftpTest001";  
               FileUpDownload.FtpPassword = "aaaaaa";  
               FileUpDownload.FtpDownload("Beyond Compare(绿色免安装).zip",  
                   Application.StartupPath + "/downloads/crm2.ra6", false);  

上传(不需要带iis部分的路径):
    OpenFileDialog op = new OpenFileDialog();  
                op.InitialDirectory = Application.StartupPath;  
                op.RestoreDirectory = true;  
                op.Filter = "压缩文件(*.zip)|*.zip|压缩文件(*.rar)|*.rar|所有文件(*.*)|*.*";  
                if (op.ShowDialog() == DialogResult.OK)  
                {                 
                    string aa = op.FileName;                 
                    FileUpDownload.FtpServerIP = "192.168.1.1";  
                    FileUpDownload.FtpUserID = "ftpTest001";  
                    FileUpDownload.FtpPassword = "aaaaaa";  
                    //全路径  
                    FileUpDownload.FtpUploadFile(aa);                
                }