C# FTP上传下载 代码

页面导航:首页 > 软件编程 > C#教程 > C# FTP上传下载 代码

C# FTP上传下载 代码

来源: 作者: 时间:2016-01-15 14:58 【

using System;using System Collections Generic;using System Linq;using System Text;using System Net;using System IO;namespace JianKunKing Common Ftp{ ftp方
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace JianKunKing.Common.Ftp
{
    /// 
    /// ftp方式文件上传
    /// 
    public static class FileUpDownload
    {
        #region 变量属性
        /// 
        /// Ftp服务器ip
        /// 
        public static string FtpServerIP = string.Empty;
        /// 
        /// Ftp 指定用户名
        /// 
        public static string FtpUserID = string.Empty;
        /// 
        /// Ftp 指定用户密码
        /// 
        public static string FtpPassword = string.Empty;

        #endregion

        #region 从FTP服务器下载文件,指定本地路径和本地文件名
        /// 
        /// 从FTP服务器下载文件,指定本地路径和本地文件名
        /// 
        ///远程文件名
        ///保存本地的文件名(包含路径)
        ///是否启用身份验证(false:表示允许用户匿名下载)
        ///报告进度的处理(第一个参数:总大小,第二个参数:当前进度)
        /// 是否下载成功
        public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action 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服务器
        /// 
        /// 上传文件到FTP服务器
        /// 
        ///本地带有完整路径的文件名
        ///报告进度的处理(第一个参数:总大小,第二个参数:当前进度)
        /// 是否下载成功
        public static bool FtpUploadFile(string localFullPath, Action 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);              
            }

/

 

 

 



 

Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<