using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;

namespace ZB.QueueSys.Common
{
    /// <summary>
    /// FTP帮助类,目前仅支持上传文件
    /// </summary>
    public class FTPHelper
    {
        private static FTPHelper instance;
        public static FTPHelper Instance
        {
            get
            {
                if (instance == null) instance = new FTPHelper(PubVariable.FtpServerIP,
                    PubVariable.FtpServerPort, PubVariable.FtpServerUsername, PubVariable.FtpServerPassword);
                return FTPHelper.instance;
            }
        }

        #region 字段构造
        string FtpURI;
        string FtpUserID;
        string FtpServerIP;
        string FtpServerPort;
        string FtpPassword;

        /// <summary>  
        /// 连接FTP服务器
        /// </summary>  
        /// <param name="ftpServerIP">FTP连接地址</param> 
        /// <param name="ftpServerPort">FTP服务端口</param> 
        /// <param name="ftpUserID">用户名</param>  
        /// <param name="ftpPassword">密码</param>  
        public FTPHelper(string ftpServerIP, string ftpServerPort, string ftpUserID, string ftpPassword)
        {
            this.FtpServerIP = ftpServerIP;
            this.FtpServerPort = ftpServerPort;
            this.FtpUserID = ftpUserID;
            this.FtpPassword = ftpPassword;
            if (!string.IsNullOrWhiteSpace(ftpServerPort)) this.FtpURI = "ftp://" + FtpServerIP + ":" + FtpServerPort + "/";
            else this.FtpURI = "ftp://" + FtpServerIP + "/";
        }
        #endregion

        #region 上传
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="localFilePath">本地文件路径</param>
        /// <param name="ftpSubPath">ftp端子目录(不包含ftp://ip/信息,可包含文件名信息)。\n如"abc/123"或者"abc/123.test.jpg"</param>
        public bool UploadFile(string localFilePath, string ftpSubPath)
        {
            FileInfo fileInf = new FileInfo(localFilePath);
            if (!fileInf.Exists) return false;

            WebClient client = new WebClient();//上传改用WebClient方式
            client.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
            client.Proxy = null;
            try
            {
                string desPath = "";
                if (string.IsNullOrWhiteSpace(ftpSubPath)) desPath = FtpURI + fileInf.Name;
                else if (ftpSubPath.LastIndexOf('.') > ftpSubPath.LastIndexOf('/'))//ftpSubPath为abc/test.jpg的格式
                    desPath = FtpURI + ftpSubPath;
                else desPath = FtpURI + ftpSubPath + "/" + fileInf.Name;

                CheckAndCreateFtpDir(ftpSubPath);
                client.UploadFile(desPath, localFilePath);
            }
            catch (Exception ex)
            {
                LogHelper.Default.SaveText("FTPHelper UploadFile:" + ex.Message + ex.StackTrace);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 上传byte[]到服务器指定文件
        /// </summary>
        /// <param name="localFileBytes">要上传的数据内容(byte[]类型)</param>
        /// <param name="ftpSubPath">ftp端子目录,必须包含文件名,但不包含ftp://ip/信息,如abc/123/test.jpg</param>
        public bool UploadData(byte[] localFileBytes, string ftpSubPath)
        {
            WebClient client = new WebClient();//上传改用WebClient方式
            client.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
            client.Proxy = null;

            try
            {
                string desPath = "";
                if (string.IsNullOrWhiteSpace(ftpSubPath)) return false;
                else desPath = FtpURI + ftpSubPath;

                CheckAndCreateFtpDir(ftpSubPath);
                client.UploadData(desPath, localFileBytes);
            }
            catch (Exception ex)
            {
                LogHelper.Default.SaveText("FTPHelper UploadData:" + ex.Message + ex.StackTrace);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 上传Bitmap到服务器指定文件
        /// </summary>
        /// <param name="bitmap">要上传的数据内容(bitmap类型)</param>
        /// <param name="ftpSubPath">ftp端子目录,必须包含文件名,但不包含ftp://ip/信息,如abc/123/test.jpg</param>
        public bool UploadData(Bitmap bitmap, string ftpSubPath)
        {
            if (bitmap == null) return false;
            return UploadData(BitmapToBytes(bitmap), ftpSubPath);
        }

        /// <summary>
        /// 将Bitmap转换为byte[]
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private byte[] BitmapToBytes(Bitmap bitmap)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                return data;
            }
        }

        #endregion

        #region 目录检测并创建
        /// <summary>
        /// 检查ftp子目录ftpDestFilePath中的各个子目录是否存在,不存在则创建
        /// </summary>
        /// <param name="ftpDestFilePath">ftp目录中的子目录</param>
        private void CheckAndCreateFtpDir(string ftpDestFilePath)
        {
            string dirStr = ftpDestFilePath;
            if (ftpDestFilePath.LastIndexOf('.') > ftpDestFilePath.LastIndexOf('/'))
                dirStr = ftpDestFilePath.Substring(0, ftpDestFilePath.LastIndexOf('/'));//这种情况带文件名,如"abc/123/test.txt"
            string[] subDirs = dirStr.Split('/');

            string curDir = "";
            for (int i = 0; i < subDirs.Length; i++)
            {
                string subDir = subDirs[i];
                curDir += subDir + "/";
                if (!DirectoryIsExist(curDir)) MakeFTPDir(curDir);
            }
        }

        /// <summary>
        /// 检测ftp目录下的subDir子目录是否存在
        /// </summary>
        /// <param name="subDir"></param>
        /// <returns>false不存在,true存在</returns>
        public bool DirectoryIsExist(string subDir)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpURI + subDir));
                reqFTP.UseBinary = true;
                reqFTP.Proxy = null;
                reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string line = reader.ReadLine();

                reader.Close();
                response.Close();

                var result = line != null;
                return result;
            }
            catch (Exception ex)
            {
                LogHelper.Default.SaveText("FTPHelper DirectoryIsExist:" + ex.Message + ex.StackTrace);
                return false;
            }
        }

        /// <summary>  
        /// 创建ftp子文件夹
        /// </summary>   
        public bool MakeFTPDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpURI + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Proxy = null;
                reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Default.SaveText("FTPHelper MakeFTPDir:" + ex.Message + ex.StackTrace);
                return false;
            }
        }
        #endregion

    }
}

  

原文地址:http://www.cnblogs.com/YYkun/p/16836982.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性