c# 操作FTP文件类

c# 操作FTP文件类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;


namespace RCP.Web.Common
{
    /// 
    /// FTP传输工具对象
    /// 
    public sealed class FTPUtils
    {
        private string _serverIP;
        private string _userID;
        private string _password;
        private FtpWebRequest reqFTP;

        public FTPUtils(string serverIP, string userID, string password)
        {
            this._password = password;
            this._serverIP = serverIP;
            this._userID = userID;
        }

        #region 连接
        /// 
        /// 连接
        /// 
        /// 
        public void Connect(string path)//连接ftp
        {
            // 根据uri创建FtpWebRequest对象
            if (reqFTP != null)
            {
                try
                {
                    reqFTP.Abort();
                }
                catch { }
            }
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
            // 指定数据传输类型
            reqFTP.UseBinary = true;
            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(_userID, _password);
        }
        #endregion

        #region 获取文件列表
        /// 
        /// 获取文件列表
        /// 
        /// 
        /// 
        /// 
        private string[] GetFileList(string path, string method)//上面的代码示例了如何从ftp服务器上获得文件列表
        {
            StringBuilder result = new StringBuilder();
            try
            {
                Connect(path);
                reqFTP.Method = method;
                using (WebResponse response = reqFTP.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        string content = reader.ReadToEnd();
                        if (!string.IsNullOrEmpty(content))
                        {
                            return content.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        }
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
        {
            return GetFileList("ftp://" + _serverIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
        }
        public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
        {
            return GetFileList("ftp://" + _serverIP + "/", WebRequestMethods.Ftp.ListDirectory);
        }
        #endregion

        #region 上传文件
        /// 
        /// 上传文件
        /// 
        /// 上传文件的全路径
        /// 文件夹名,根目录请填写"",不存在则自动创建
        /// 是否使用GUID文件名,默认为true
        /// 
        public string Upload(string filename, string dirName, bool isGuidName) //上面的代码实现了从ftp服务器上载文件的功能
        {
            bool isGuid = true;
            string savaName = "";
            isGuid = isGuidName;
            dirName = dirName.Trim('/').TrimEnd('/');
            string path = this._serverIP.Replace("\\", "/");
            FileInfo fileInf = new FileInfo(filename);
            if (isGuid)
            {
                string[] temp = fileInf.Name.Split('.');
                savaName = Guid.NewGuid() + "." + temp[temp.Length - 1];
            }
            else
            {
                savaName = fileInf.Name;
            }
            MakeMultipleDir(dirName);
            savaName = dirName == "" ? savaName : dirName + "/" + savaName;
            string uri = "ftp://" + path + "/" + savaName;
            Connect(uri);//连接         
            // 默认为true,连接不会被关闭
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;
            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 上传文件时通知服务器文件的大小
            reqFTP.ContentLength = fileInf.Length;
            // 缓冲大小设置为kb 
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            // 打开一个文件流(System.IO.FileStream) 去读上传的文件
            FileStream fs = fileInf.OpenRead();
            try
            {
                // 把上传的文件写入流
                Stream strm = reqFTP.GetRequestStream();
                // 每次读文件流的kb
                contentLen = fs.Read(buff, 0, buffLength);
                // 流内容没有结束
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入upload stream 
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                // 关闭两个流
                strm.Close();
                fs.Close();
                //errorinfo = "完成";
                return "/" + savaName;
            }
            catch (Exception ex)
            {
                //errorinfo = string.Format("因{0},无法完成上传", ex.Message);
                return "";
            }
        }

        /// 
        /// 直接传数据流的方式
        /// 
        /// 数据流
        /// ftp路径
        /// 文件名称
        /// 
        public string UpdateStream(Stream streamRead, string dirName, string fileName)
        {
            string savaName = "";
            dirName = dirName.Trim('/').TrimEnd('/');
            string path = this._serverIP.Replace("\\", "/");
            MakeMultipleDir(dirName);
            savaName = dirName == "" ? savaName : dirName + "/" + fileName;
            string uri = "ftp://" + path + "/" + savaName;
            Connect(uri);//连接         
            // 默认为true,连接不会被关闭
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;
            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 上传文件时通知服务器文件的大小  
            reqFTP.ContentLength = streamRead.Length;
            // 缓冲大小设置为5kb  
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            try
            {
                Stream streamWrite = reqFTP.GetRequestStream();
                streamRead.Flush();
                streamRead.Position = 0;
                contentLen = streamRead.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    streamWrite.Write(buff, 0, contentLen);
                    contentLen = streamRead.Read(buff, 0, buffLength);
                }
                // 关闭两个流  
                streamWrite.Close();

                return "/"+savaName;
            }
            catch (Exception)
            {
                return "";
            }
        }


        /// 
        /// 上传图片
        /// 
        /// 图片
        /// ftp地址
        /// 文件名称
        /// 图片格式
        /// 
        public string UploadImg(Image img, string dirName, string fileName,ImageFormat imgFormat)
        {
            //获取图片流
            MemoryStream streamRead = new MemoryStream();
            img.Save(streamRead, imgFormat);
            return UpdateStream(streamRead, dirName, fileName);
        }
        #endregion

        #region 删除文件
        /// 
        /// 删除文件
        /// 
        /// 文件的相对路径
        public bool DeleteFileName(string fileName)
        {
            try
            {
                //FileInfo fileInf = new FileInfo(fileName);
                string uri = "ftp://" + _serverIP + "/" + fileName;
                Connect(uri);//连接         
                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "删除错误");
                return false;
            }
        }
        #endregion

        #region 在ftp上创建目录
        public void MakeMultipleDir(string dirName)
        {
            if (dirName != "")
            {
                string[] dirs = dirName.Trim('/').TrimEnd('/').Split('/');
                if (dirs.Length > 0)
                {
                    string oldpath = "";   //文件夹完整路径
                    string nowdir = "";    //当前文件夹名称
                    bool b = true;         //是否存在该文件夹
                    for (int i = 0; i < dirs.Length; i++)
                    {
                        b = true;
                        string[] list = GetFileList(oldpath.TrimEnd('/'));
                        if (list != null)
                        {
                            for (int z = 0; z < list.Length; z++)
                            {
                                if (i > 0)
                                    nowdir = dirs[i - 1] + "/" + dirs[i];
                                else
                                    nowdir = dirs[i];
                                if (list[z] == nowdir)
                                {
                                    b = false;
                                    break;
                                }
                            }
                        }
                        oldpath += dirs[i] + "/";
                        if (b)
                            MakeDir(oldpath.TrimEnd('/'));
                    }
                }
                else
                {
                    MakeDir(dirName);
                }
            }
        }

        /// 
        /// 在ftp上创建目录
        /// 
        /// 
        public void MakeDir(string dirName)
        {
            try
            {
                string uri = "ftp://" + _serverIP + "/" + dirName;
                Connect(uri);//连接      
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 删除ftp上目录
        /// 
        /// 删除ftp上目录
        /// 
        /// 
        public void DelDir(string dirName)
        {
            try
            {
                string uri = "ftp://" + _serverIP + "/" + dirName;
                Connect(uri);//连接      
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 获得ftp上文件大小
        /// 
        /// 获得ftp上文件大小
        /// 
        /// 
        /// 
        public long GetFileSize(string filename)
        {
            long fileSize = 0;
            filename = filename.Replace("\\", "/");
            try
            {
                string uri = "ftp://" + filename;
                this.Connect(uri);//连接      
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                fileSize = response.ContentLength;
                response.Close();
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message);
            }
            return fileSize;
        }
        #endregion

        #region 重命名对象
        /// 
        /// 重命名对象
        /// 
        /// 
        /// 
        public void Rename(string filePath, string newFilename)
        {
            try
            {
                string uri = "ftp://" + _serverIP + "/" + filePath;
                Connect(uri);//连接
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 获得文件明细
        /// 
        /// 获得文件明细
        /// 
        /// 
        public string[] GetFilesDetailList()
        {
            return GetFileList("ftp://" + _serverIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
        }
        /// 
        /// 获得文件明细
        /// 
        /// 
        /// 
        public string[] GetFilesDetailList(string path)
        {
            path = path.Replace("\\", "/");
            return GetFileList("ftp://" + _serverIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
        }
        #endregion
    }


}

使用方法:

上传图片到ftp

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using RCP.Web.Common;



namespace Import_Advtisement
{
    class FileTransfer
    {

        public string sendPicture(string filename,string dirname,string city)
        {
         
           FTPUtils ftp = new FTPUtils("192.168.0.157", "zoe", "123456");         
            // string filename = this.FileUpload1.FileName.Trim();
           // string filename = this.FileUpload1.PostedFile.FileName.Trim();
            // string mappath = Server.MapPath(filename);
            //ftp.Connect("ftp://" + "192.168.0.46");
            string[] list = ftp.GetFileList();
            string result_upload = ftp.Upload(filename, dirname,false);
            //ftp.DeleteFileName(result_upload);
            //ftp.MakeDir("img_new/img2_new");
            //ftp.Rename("img", "img_new");
            //string[] list1 = ftp.GetFilesDetailList();
            return result_upload;


        }


    }



}



例子下载:
http://download.csdn.net/detail/xingjuan2008/5664075
http://download.csdn.net/detail/tttff/1926458
http://download.csdn.net/detail/xiaodenanhai/5978909
http://download.csdn.net/detail/wsj1983920/855387

你可能感兴趣的:(c#)