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
{
    /// <summary>
    /// FTP传输工具对象
    /// </summary>
    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 连接
        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="path"></param>
        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 获取文件列表
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="path"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        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 上传文件
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="filename">上传文件的全路径</param>
        /// <param name="dirName">文件夹名,根目录请填写"",不存在则自动创建</param>
        /// <param name="isGuidName">是否使用GUID文件名,默认为true</param>
        /// <returns></returns>
        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 "";
            }
        }

        /// <summary>
        /// 直接传数据流的方式
        /// </summary>
        /// <param name="streamRead">数据流</param>
        /// <param name="dirName">ftp路径</param>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        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 "";
            }
        }


        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="img">图片</param>
        /// <param name="dirName">ftp地址</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="imgFormat">图片格式</param>
        /// <returns></returns>
        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 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName">文件的相对路径</param>
        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);
                }
            }
        }

        /// <summary>
        /// 在ftp上创建目录
        /// </summary>
        /// <param name="dirName"></param>
        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上目录
        /// <summary>
        /// 删除ftp上目录
        /// </summary>
        /// <param name="dirName"></param>
        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上文件大小
        /// <summary>
        /// 获得ftp上文件大小
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        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 重命名对象
        /// <summary>
        /// 重命名对象
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="newFilename"></param>
        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 获得文件明细
        /// <summary>
        /// 获得文件明细
        /// </summary>
        /// <returns></returns>
        public string[] GetFilesDetailList()
        {
            return GetFileList("ftp://" + _serverIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
        }
        /// <summary>
        /// 获得文件明细
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        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

相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页
实付 69.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值