设为首页 收藏本站
查看: 3295|回复: 0

FTP协议操作

[复制链接]

尚未签到

发表于 2015-5-30 10:24:32 | 显示全部楼层 |阅读模式
  FTP协议操作代码
  采用MS的FTP协议封装
  

DSC0000.gif using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.DirectoryServices.Protocols;

namespace Vancl.FileUtility
DSC0001.gif DSC0002.gif DSC0003.gif {
DSC0004.gif     public class FtpCmd
DSC0005.gif DSC0006.gif     {
        创建文件夹#region 创建文件夹
        /**////
        /// 创建文件夹:不实现级联创建
        /// 返回:true成功,false失败
        ///
        /// 基Uri字符串:如ftp://192.168.1.190:21
        /// 目标目录名,相对路径:如/FTF
        /// 用户名
        /// 用户密码
DSC0007.gif         ///
        public static bool CreateFtpDirectory(string BaseUriStr, string AimUriStr, string UserName, string UserPwd)
        {
            Uri BaseUri = new Uri(BaseUriStr);
            Uri AimUri = new Uri(BaseUri, AimUriStr);
            FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create(AimUri);
            FtpRequest.KeepAlive = true;
            FtpRequest.Timeout = 2000;
            FtpRequest.UsePassive = false;
            NetworkCredential FtpCred = new NetworkCredential(UserName, UserPwd);
            CredentialCache FtpCache = new CredentialCache();
            FtpCache.Add(AimUri, AuthType.Basic.ToString(), FtpCred);
            FtpRequest.Credentials = FtpCache;
            FtpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;

            try
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
                if (FtpResponse.StatusCode == FtpStatusCode.PathnameCreated)
                {
                    FtpResponse.Close();
                    return true;
                }
                else
                {
                    FtpResponse.Close();
                    return false;
                }
            }
            catch (WebException e)
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)e.Response;
                if (FtpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    //文件已存在,返回True
                    FtpResponse.Close();
                    return true;
                }
                else
                {
                    FtpResponse.Close();
                    return false;
                }
            }
        }
        /**////
        /// 创建文件夹:实现级联创建
        /// 返回:true成功,false失败
        ///
        /// 基Uri字符串:如ftp://192.168.1.190:21
        /// 目标目录名,相对路径:如/FTF/FTF1/FTF2/FTF3
        /// 用户名
        /// 用户密码
        ///
        public static bool CreateFtpListDirectory(string BaseUriStr, string AimUriStr, string UserName, string UserPwd)
        {
            string[] AimUriArray = AimUriStr.TrimStart('/').Split('/');
            string AimUriCache = string.Empty;
            for (int i = 0; i < AimUriArray.Length; i++)
            {
                AimUriCache += "/" + AimUriArray;
                if (CreateFtpDirectory(BaseUriStr, AimUriCache, UserName, UserPwd))
                {
                    continue;
                }
                else
                {
                    if (CreateFtpDirectory(BaseUriStr, AimUriCache, UserName, UserPwd))
                    {
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return true;
        }
        #endregion

        删除文件夹#region 删除文件夹
        /**////
        /// 删除文件夹,不实现级联删除
        /// 返回:true成功,false失败
        ///
        /// 基Uri字符串:如ftp://192.168.1.190:21
        /// 目标目录,相对路径:如/FTF/FTFDEL
        /// 用户名
        /// 用户密码
        ///
        public static bool DeleteFtpDirectory(string BaseUriStr, string AimUriStr, string UserName, string UserPwd)
        {
            Uri BaseUri = new Uri(BaseUriStr);
            Uri AimUri = new Uri(BaseUri, AimUriStr);
            FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create(AimUri);
            FtpRequest.KeepAlive = true;
            FtpRequest.Timeout = 2000;
            FtpRequest.UsePassive = false;
            NetworkCredential FtpCred = new NetworkCredential(UserName, UserPwd);
            CredentialCache FtpCache = new CredentialCache();
            FtpCache.Add(AimUri, AuthType.Basic.ToString(), FtpCred);
            FtpRequest.Credentials = FtpCache;
            FtpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;

            try
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
                if (FtpResponse.StatusCode == FtpStatusCode.FileActionOK)
                {
                    FtpResponse.Close();
                    return true;
                }
                else
                {
                    FtpResponse.Close();
                    return false;
                }
            }
            catch (WebException e)
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)e.Response;
                //如果返回信息表示文件不可操作或不存在,表明文件夹已经被删除
                if (FtpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    FtpResponse.Close();
                    return true;
                }
                else
                {
                    //返回其他错误:可能出现问题
                    FtpResponse.Close();
                    return false;
                }
            }
        }
        /**////
        /// 删除文件夹,实现级联删除
        /// 返回:true成功,false失败
        ///
        /// 基Uri字符串:如ftp://192.168.1.190:21
        /// 目标目录,相对路径:如/FTF/FTFDEL
        /// 用户名
        /// 用户密码
        ///
        public static bool DeleteFtpListDirectory(string BaseUriStr, string AimUriStr, string UserName, string UserPwd)
        {
            List DirectoryDetailList = ListFtpDirectory(BaseUriStr, AimUriStr, UserName, UserPwd);
            foreach (string ListDetail in DirectoryDetailList)
            {
                if (ListDetail.EndsWith("|D"))
                {
                    //删除文件夹内容
                    if (ListFtpDirectory(BaseUriStr, AimUriStr + "/" + ListDetail.Split('|')[0], UserName, UserPwd).Count == 0)
                    {
                        if (!DeleteFtpDirectory(BaseUriStr, AimUriStr + "/" + ListDetail.Split('|')[0], UserName, UserPwd))
                        {
                            return false;
                        }
                    }
                    else
                    {
                        if (!DeleteFtpListDirectory(BaseUriStr, AimUriStr + "/" + ListDetail.Split('|')[0], UserName, UserPwd))
                        {
                            return false;
                        }
                    }
                }
                if (ListDetail.EndsWith("|F"))
                {
                    //删除文件
                    if (!DeleteFtpFile(BaseUriStr, AimUriStr + "/" + ListDetail.Split('|')[0], UserName, UserPwd))
                    {
                        return false;
                    }
                }
            }
            //删除当前文件夹
            if (!DeleteFtpDirectory(BaseUriStr, AimUriStr, UserName, UserPwd))
            {
                return false;
            }

            return true;
        }
        #endregion

        获取文件夹内文件和文件夹列表信息#region 获取文件夹内文件和文件夹列表信息
        /**////
        /// 获取文件夹内文件信息
        ///
        /// 基Uri:如ftp://192.168.1.190:21
        /// 目标目录,相对路径:如/FTF/FTF1
        /// 用户名
        /// 用户密码
        ///
        public static List ListFtpDirectory(string BaseUriStr, string AimUriStr, string UserName, string UserPwd)
        {
            Uri BaseUri = new Uri(BaseUriStr);
            Uri AimUri = new Uri(BaseUri, AimUriStr);
            FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create(AimUri);
            FtpRequest.KeepAlive = true;
            FtpRequest.ReadWriteTimeout = 10000;
            FtpRequest.UsePassive = false;
            NetworkCredential FtpCred = new NetworkCredential(UserName, UserPwd);
            CredentialCache FtpCache = new CredentialCache();
            FtpCache.Add(AimUri, AuthType.Basic.ToString(), FtpCred);
            FtpRequest.Credentials = FtpCache;
            FtpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            try
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
                StreamReader srd = new StreamReader(FtpResponse.GetResponseStream(), Encoding.GetEncoding("GB2312"));
                string ResponseBackStr = srd.ReadToEnd();
                srd.Close();
                FtpResponse.Close();

                string[] ListDetails = ResponseBackStr.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                List RtnList = new List();
                foreach (string ListDetail in ListDetails)
                {
                    if (ListDetail.StartsWith("d") && (!ListDetail.EndsWith(".")))
                    {
                        string FtpDirName = ListDetail.Substring(ListDetail.IndexOf(':') + 3).TrimStart();
                        RtnList.Add(FtpDirName + "|D");
                    }
                    else if (ListDetail.StartsWith("-"))
                    {
                        string FtpDirName = ListDetail.Substring(ListDetail.IndexOf(':') + 3).TrimStart();
                        RtnList.Add(FtpDirName + "|F");
                    }
                }

                return RtnList;
            }
            catch (WebException e)
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)e.Response;
                FtpResponse.Close();

                return new List();
            }
        }
        #endregion

        删除指定文件#region 删除指定文件
        /**////
        /// 删除指定文件
        ///
        /// 基Uri字符串,如ftp://192.168.1.190:21
        /// 目标目录,相对路径:如/FTF/FTFDEL
        /// 用户名
        /// 用户密码
        ///
        public static bool DeleteFtpFile(string BaseUriStr, string AimUriStr, string UserName, string UserPwd)
        {
            Uri BaseUri = new Uri(BaseUriStr);
            Uri AimUri = new Uri(BaseUri, AimUriStr);
            FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create(AimUri);
            FtpRequest.KeepAlive = true;
            FtpRequest.Timeout = 2000;
            FtpRequest.UsePassive = false;
            NetworkCredential FtpCred = new NetworkCredential(UserName, UserPwd);
            CredentialCache FtpCache = new CredentialCache();
            FtpCache.Add(AimUri, AuthType.Basic.ToString(), FtpCred);
            FtpRequest.Credentials = FtpCache;
            FtpRequest.Method = WebRequestMethods.Ftp.DeleteFile;

            try
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
                if (FtpResponse.StatusCode == FtpStatusCode.FileActionOK)
                {
                    FtpResponse.Close();
                    return true;
                }
                else
                {
                    FtpResponse.Close();
                    return false;
                }
            }
            catch (WebException e)
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)e.Response;
                if (FtpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    FtpResponse.Close();
                    return true;
                }
                else
                {
                    FtpResponse.Close();
                    return false;
                }
            }
        }
        #endregion

        上传文件#region 上传文件
        /**////
        /// 上传文件到指定位置
        ///
        /// 基Uri字符串,如ftp://192.168.1.190:21
        /// 目标位置,相对路径:如/FTF/FTFDEL/K.pdf
        /// 用户名
        /// 用户密码
        /// 源文件位置
        ///
        public static bool UploadFtpFile(string BaseUriStr, string AimUriStr, string UserName, string UserPwd, string SrcFilePath)
        {
            Uri BaseUri = new Uri(BaseUriStr);
            Uri AimUri = new Uri(BaseUri, AimUriStr);
            FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create(AimUri);
            FtpRequest.KeepAlive = true;
            FtpRequest.ReadWriteTimeout = 10000;
            FtpRequest.UsePassive = false;
            NetworkCredential FtpCred = new NetworkCredential(UserName, UserPwd);
            CredentialCache FtpCache = new CredentialCache();
            FtpCache.Add(AimUri, AuthType.Basic.ToString(), FtpCred);
            FtpRequest.Credentials = FtpCache;
            FtpRequest.Method = WebRequestMethods.Ftp.UploadFile;

            try
            {
                Stream stm = FtpRequest.GetRequestStream();
                byte[] RequestByteArray = File.ReadAllBytes(SrcFilePath);
                stm.Write(RequestByteArray, 0, RequestByteArray.Length);
                stm.Close();

                FtpWebResponse FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
                if (FtpResponse.StatusCode == FtpStatusCode.ClosingData)
                {
                    FtpResponse.Close();
                    FileInfo FI = new FileInfo(SrcFilePath);

                    if (GetFtpFileSize(BaseUriStr, AimUriStr, UserName, UserPwd) == FI.Length)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    FtpResponse.Close();
                    return false;
                }
            }
            catch (WebException e)
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)e.Response;
                FtpResponse.Close();

                return false;
            }
        }
        /**////
        /// 获取文件尺寸
        /// 返回文件字节数
        ///
        /// 基Uri字符串,如ftp://192.168.1.190:21
        /// 目标位置,相对路径:如/FTF/FTFDEL/K.pdf
        /// 用户名
        /// 用户密码
        ///
        public static int GetFtpFileSize(string BaseUriStr, string AimUriStr, string UserName, string UserPwd)
        {
            Uri BaseUri = new Uri(BaseUriStr);
            Uri AimUri = new Uri(BaseUri, AimUriStr);
            FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create(AimUri);
            FtpRequest.KeepAlive = true;
            FtpRequest.ReadWriteTimeout = 10000;
            FtpRequest.UsePassive = false;
            NetworkCredential FtpCred = new NetworkCredential(UserName, UserPwd);
            CredentialCache FtpCache = new CredentialCache();
            FtpCache.Add(AimUri, AuthType.Basic.ToString(), FtpCred);
            FtpRequest.Credentials = FtpCache;
            FtpRequest.Method = WebRequestMethods.Ftp.GetFileSize;

            try
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
                long FileSize = FtpResponse.ContentLength;
                FtpResponse.Close();

                return Convert.ToInt32(FileSize);
            }
            catch
            {
                return -1;
            }
        }
        #endregion

        文件重命名#region 文件重命名
        /**////
        /// 文件重命名、文件移动
        ///
        /// 基Uri字符串,如ftp://192.168.1.190:21
        /// 源位置,相对路径:如/FTF/FTFDEL/K.pdf
        /// 目标位置,相对路径:如/FTF/FTFDEL/K.pdf
        /// 用户名
        /// 用户密码
        ///
        public static bool RenameFtpFile(string BaseUriStr, string SrcUriStr, string AimUriStr, string UserName, string UserPwd)
        {
            Uri BaseUri = new Uri(BaseUriStr);
            Uri AimUri = new Uri(BaseUri, SrcUriStr);
            FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create(AimUri);
            FtpRequest.KeepAlive = true;
            FtpRequest.ReadWriteTimeout = 10000;
            FtpRequest.UsePassive = false;
            NetworkCredential FtpCred = new NetworkCredential(UserName, UserPwd);
            CredentialCache FtpCache = new CredentialCache();
            FtpCache.Add(AimUri, AuthType.Basic.ToString(), FtpCred);
            FtpRequest.Credentials = FtpCache;
            FtpRequest.Method = WebRequestMethods.Ftp.Rename;
            FtpRequest.RenameTo = AimUriStr;

            try
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)FtpRequest.GetResponse();
                if (FtpResponse.StatusCode == FtpStatusCode.FileActionOK)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch(WebException e)
            {
                FtpWebResponse FtpResponse = (FtpWebResponse)e.Response;
                FtpResponse.Close();
                return false;
            }
        }
        #endregion
    }
DSC0008.gif }  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-72097-1-1.html 上篇帖子: .NET中完成FTP各功能操作 下篇帖子: linux下访问ftp服务器和文件传输
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表