先奉献一个测试地址,ftp内的文件请勿删除,谢谢

FtpEntity fe = new FtpEntity("wjshan0808.3vhost.net", "wjshan0808", "1234567890");

由于代码量较多,只抽出一部分,详细代码请移步  ftp://wjshan0808.3vhost.net/FtpEntity/或 随笔后面有源码下载地址

部分字段#region fieldsprivate const string PATTERN = @"^([dlb-])([rwx-]{9})\s+(\d{1,})\s+(\w+)\s+(.+?\b)\s+(\d{1,})\s+(.+?)\s+(\d{1,2})\s+(\d{2}:?\d{2})\s+(.+)$";private const int DYNAMICINCREASEVALUE = 1024 * 512;//512KBprivate const int DYNAMICIMCEPTVALUE = 1024 * 64;//64KB;private static ReaderWriterLock _lok = new ReaderWriterLock();private int _dynamicBufferSize = 0;private bool _isDownloadCheck = true;private bool _isUploadCheck = false;private Dictionary<Uri, long> _dicFileSize = null;private int _sendBufferSize = 1024 * 128;//128KB#endregion#region props/// <summary>/// 当文件数据上传完成时发生/// </summary>public event UploadCompletedEventHandler UploadCompleted;/// <summary>/// 获取或设置上传数据的缓冲区大小/// </summary>public int SendBufferSize{get { return _sendBufferSize; }set{if (value < 1)value = 1024 * 128;_lok.AcquireWriterLock(1000);try{_sendBufferSize = value;}finally{_lok.ReleaseWriterLock();}}}/// <summary>/// 获取请求FTP服务器的协议地址/// </summary>public string Address{get { return string.Format("ftp://{0}:{1}", _address, Port); }}/// <summary>/// 获取或设置相对FTP根目录的绝对路径,默认为Ftp根目录/// </summary>public string AbsolutePath{get { return _absolutePath; }set{IsNull(ref value);while (value.StartsWith("/")){value = value.TrimStart('/');}if (value.IndexOfAny(Path.GetInvalidPathChars()) >= 0)throw new ArgumentException("RelativeUrl:Invalid Value");_absolutePath = value;}}/// <summary>/// 获取请求FTP服务器的解析地址/// </summary>public string ResolveUrl{get { return Path.Combine(Address, AbsolutePath).Replace(@"\", "/"); }}#endregion

1.获取详细列表

        /// <summary>/// 获取 AbsolutePath (属性值)下的文件(夹)的详细列表/// </summary>/// <param name="total">总用量</param>/// <param name="absolutePath">目标地址</param>/// <returns>文件(夹)详细信息</returns>public FtpDirectoryDetails[] ListDirectoryDetails(out int total, string absolutePath = null){if (absolutePath != null && absolutePath != string.Empty)AbsolutePath = absolutePath;using (FtpWebResponse response = SyncInternalCommon(WebRequestMethods.Ftp.ListDirectoryDetails)){total = 0;IList<FtpDirectoryDetails> fddes = new List<FtpDirectoryDetails>(16);StreamReader reader = null;try{if (response.StatusCode == FtpStatusCode.OpeningData){reader = new StreamReader(response.GetResponseStream(), Encoding.Default, true);}if (reader == null) throw new ArgumentNullException("reader");while (!reader.EndOfStream){string line = reader.ReadLine();MatchCollection mc = Regex.Matches(line, PATTERN, RegexOptions.CultureInvariant);if (mc.Count == 1){object[] tmp = new object[11];mc[0].Groups.CopyTo(tmp, 0);fddes.Add(new FtpDirectoryDetails(tmp));}else //total
                        {total = int.Parse(Regex.Match(line, @"\d{1,}", RegexOptions.CultureInvariant).Value);}}return fddes.ToArray();}catch (Exception ex){Log(ex);throw ex;}finally{if (reader != null)reader.Close();}}}

View Code

目录详细信息类

    /// <summary>/// 目录文件信息/// </summary>public struct FtpDirectoryDetails{public FtpDirectoryType Type { get; set; }public FtpDirectoryAccess[] Access { get; set; }public short Count { get; set; }public string User { get; set; }public string Group { get; set; }public long Size { get; set; }public DateTime LastModified { get; set; }//public string Year { get; set; }public string Name { get; set; }public FtpDirectoryDetails(object[] details){Type = FtpDirectoryType.Unknow;Access = new FtpDirectoryAccess[3] { FtpDirectoryAccess.None, FtpDirectoryAccess.None, FtpDirectoryAccess.None };Count = short.Parse(details[3].ToString());User = details[4].ToString();Group = details[5].ToString();Size = long.Parse(details[6].ToString());LastModified = DateTime.MinValue;Name = details[10].ToString();//
            SetType(details[1].ToString());SetAccess(details[2].ToString());SetLastModified(details[7].ToString(), details[8].ToString(), details[9].ToString());}private void SetLastModified(string month, string day, string time0year){StringBuilder sb = new StringBuilder(16);bool contains = time0year.Contains(":");sb.Append(contains ? DateTime.Now.Year.ToString() : time0year);sb.Append(" ");sb.Append(string.Format("{0:00}", SetMonth(month)));sb.Append(" ");sb.Append(string.Format("{0:00}", day));sb.Append(" ");sb.Append(contains ? time0year : "00:00");sb.Append(":00");LastModified = DateTime.Parse(sb.ToString());}/// <summary>/// 1.英文/// 2.阿拉伯数字/// 3.两位阿拉伯数字/// 4.(2,3)+中文/// </summary>/// <param name="month"></param>/// <returns></returns>private object SetMonth(string month){if (month[month.Length - 1] <= 57)//最后一位是数字 return month;if (month[0] <= 57)//第一位是数字return month.Substring(0, month.Length - 1);if ("January".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Janreturn 1;else if ("February".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Febreturn 2;else if ("March".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Marreturn 3;else if ("April".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Aprreturn 4;else if ("May".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Mayreturn 5;else if ("June".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Junreturn 6;else if ("July".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Julreturn 7;else if ("August".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Augreturn 8;else if ("September".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Sepreturn 9;else if ("October".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Octreturn 10;else if ("November".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Novreturn 11;else//("December".StartsWith(month, StringComparison.CurrentCultureIgnoreCase))//Decreturn 12;}private void SetAccess(string access){for (int i = 0; i < access.Length; i += 3){FtpDirectoryAccess acc = FtpDirectoryAccess.None;for (int j = i; j < (i + 3); j++){switch (access[j]){case 'r':acc |= FtpDirectoryAccess.Read;break;case 'w':acc |= FtpDirectoryAccess.Write;break;case 'x':acc |= FtpDirectoryAccess.Execute;break;default:// '-':acc |= FtpDirectoryAccess.None;break;}}Access[i / 3] = acc;}}private void SetType(string type){switch (type){case "d":Type = FtpDirectoryType.Folder;break;case "-":Type = FtpDirectoryType.File;break;case "l":Type = FtpDirectoryType.Link;break;case "b":Type = FtpDirectoryType.Block;break;default:Type = FtpDirectoryType.Unknow;break;}}}

2.上传

        #region UploadCommonprotected void SyncUploadCommon(string file, bool withUnique = false, long offset = 0){CheckUrl(file, withUnique);FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);if (offset > 0)fs.Seek(offset, SeekOrigin.Begin);FtpWebRequest request = WebRequest.Create(ResolveUrl) as FtpWebRequest;request.Credentials = Credential;request.UsePassive = false;request.ContentLength = fs.Length;if (withUnique && offset == 0)request.Method = WebRequestMethods.Ftp.UploadFileWithUniqueName;elserequest.Method = offset > 0 ? WebRequestMethods.Ftp.AppendFile : WebRequestMethods.Ftp.UploadFile;string path = request.RequestUri.AbsolutePath;Stream stream = null;BinaryReader reader = null;FtpTransmissionStatus status = FtpTransmissionStatus.Ok;try{stream = request.GetRequestStream();if (stream == null)throw new ArgumentNullException("stream");reader = new BinaryReader(fs, Encoding.Default);if (reader == null)throw new ArgumentNullException("reader");while (reader.PeekChar() != -1){byte[] bt = reader.ReadBytes(_sendBufferSize);stream.Write(bt, 0, bt.Length);stream.Flush();}//GetResponse after Close
}catch (Exception ex){status = FtpTransmissionStatus.Error;Log(ex);//throw ex;
            }finally{if (reader != null)reader.Close();if (stream != null)stream.Close();if (UploadCompleted != null){Thread.Sleep(124);UploadCompleted(new object(),new UploadCompletedEventArgs(){Length = (!withUnique && IsUploadCheck) ? GetFileSize(path) : -1,//异步时文件路径会改变Path = path,FileName = (!withUnique) ? Path.GetFileName(path) : string.Empty,UploadStatus = status});}}}protected void AsyncUploadCommon(string file, long offset = 0, bool withUnique = false){CheckUrl(file, withUnique);FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);if (offset > 0)fs.Seek(offset, SeekOrigin.Begin);FtpWebRequest request = WebRequest.Create(ResolveUrl) as FtpWebRequest;request.Credentials = Credential;request.UsePassive = false;request.ContentLength = fs.Length;if (withUnique && offset == 0)request.Method = WebRequestMethods.Ftp.UploadFileWithUniqueName;elserequest.Method = offset > 0 ? WebRequestMethods.Ftp.AppendFile : WebRequestMethods.Ftp.UploadFile;FtpState state = new FtpState() { Request = request, FileStream = fs, Path = request.RequestUri.AbsolutePath, Unique = withUnique };try{IAsyncResult iar = request.BeginGetRequestStream(new AsyncCallback(UploadCallBack), state);}catch (Exception ex){Log(ex);state.Dispose();//throw ex;
            }}protected void UploadCallBack(IAsyncResult ar){FtpState state = ar.AsyncState as FtpState;if (state == null) throw new ArgumentNullException("state");if (state.Request == null) throw new ArgumentNullException("state.Request");if (state.FileStream == null) throw new ArgumentNullException("state.FileStream");FtpTransmissionStatus status = FtpTransmissionStatus.Ok;try{if (ar.IsCompleted){Stream stream = state.Request.EndGetRequestStream(ar);if (stream == null)throw new ArgumentNullException("stream");state.Stream = stream;}while (IsReadToEnd){byte[] bt = new byte[SendBufferSize];int length = state.FileStream.Read(bt, 0, bt.Length);if (length == 0) break;IAsyncResult iar = state.Stream.BeginWrite(bt, 0, length, null, null);state.Stream.EndWrite(iar);state.Stream.Flush();}//GetResponse after Close
}catch (Exception ex){status = FtpTransmissionStatus.Error;Log(ex);//throw ex;
            }finally{string path = state.Path;bool withUnique = state.Unique;state.Dispose();if (UploadCompleted != null){Thread.Sleep(124);UploadCompleted(new object(),new UploadCompletedEventArgs(){Length = (!withUnique && IsUploadCheck) ? GetFileSize(path) : -1,//异步时文件路径会改变Path = path,FileName = (!withUnique) ? Path.GetFileName(path) : string.Empty,UploadStatus = status});}}}#endregion

View Code

辅助函数

        private int DynamicBufferSize(int length){if (length == 0)length += DYNAMICIMCEPTVALUE;if (length == _dynamicBufferSize)length += DYNAMICINCREASEVALUE;length += -_dynamicBufferSize;if ((length + _dynamicBufferSize) <= 0)length += DYNAMICIMCEPTVALUE;return Interlocked.Add(ref _dynamicBufferSize, length);}private void CheckPath(string path){if (path == null)throw new ArgumentNullException(path);if (path.IndexOfAny(Path.GetInvalidPathChars()) >= 0)throw new ArgumentException("Invalid Path");if (!File.Exists(path))throw new FileNotFoundException();}private string CheckName(string value){if (value == null || value == string.Empty)throw new ArgumentNullException(value);if (value.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)throw new WarningException(value + "Invalid FileName");return value;}private void CheckUrl(string file, bool withUnique){string name = Path.GetFileName(file);string uploadname = Path.GetFileName(AbsolutePath);if (uploadname == string.Empty){AbsolutePath = AbsolutePath.TrimEnd(new char[] { '/' }) + "/" + name;}}private void IsNull(ref string value){if (value != null) return;value = string.Empty;}

测试代码

        private void btnTest_Click(object sender, EventArgs e){fe.UploadCompleted += new UploadCompletedEventHandler(Fe_UploadCompleted);try{fe.AbsolutePath = "FtpEntity";Files(@"C:\Users\Administrator\Desktop\FtpEntity\FtpEntity");}catch (Exception ex){}}public void Files(string dir){DirectoryInfo di = new DirectoryInfo(dir);foreach (DirectoryInfo item in di.GetDirectories()){string tmp1 = fe.AbsolutePath;fe.AbsolutePath += "/" + item.Name;fe.MakeDirectory();Files(item.FullName);fe.AbsolutePath = tmp1;}foreach (FileInfo fi in di.GetFiles()){string tmp2 = fe.AbsolutePath;fe.AbsolutePath += "/" + fi.Name;fe.AsyncUploadFile(fi.FullName);fe.AbsolutePath = tmp2;}}private void Fe_UploadCompleted(object sender, UploadCompletedEventArgs e){if (rtxtLog.InvokeRequired){rtxtLog.Invoke(new UploadCompletedEventHandler(Fe_UploadCompleted), new object[] { sender, e });}else{rtxtLog.Text += Environment.NewLine + "-----------";rtxtLog.Text += e.Length + Environment.NewLine+ e.FileName + Environment.NewLine+ e.FileSize + Environment.NewLine+ e.Path + Environment.NewLine+ e.UploadStatus;rtxtLog.Text += Environment.NewLine + "-----------";}}

源文件地址 http://pan.baidu.com/s/1o6rLR2y

转载于:https://www.cnblogs.com/wjshan0808/p/4945645.html

C# 实现 微软WebRequestMethods.Ftp类中的FTP操作功能相关推荐

  1. string类有可以调换方向的函数吗_String类中常用的操作

    一.获取: 1.获取字符串的长度(注意是方法,不是跟数组的属性一样的) int length(); 1 public static void getLength(){ 2 String s = &qu ...

  2. 关于学习Python的一点学习总结(44->类中的比较操作符号重写)

    84.一些比较操作的符号重写: 1.__lt__(self,other):定义小于号的行为:x<y 调用x.__lt__(y) 2.__le__(self,other):定义大于等于号的行为:x ...

  3. java中的IO操作之File类

    Java的集合框架:  类和接口存在于java.util包中. Java的IO:               类和接口存在于java.io包中. 学习方法:  文档在手,天下我有! --------- ...

  4. 用于理解C++类中静态成员的单子模式研究

    对于类中的静态成员的使用一直不懂,今天看了一位清华老师的C++课程中的一节课,里面专门利用单子模式对静态成员进行阐释(我不知道老师的姓名,讲的非常好,谢谢!).下面的记录和理解都是根据我个人的理解和语 ...

  5. 编写一个用户类(Sysuser),属性包括用户名、真实姓名、年龄、出生日期、密码,类方法中包含单独修改用户年龄、判断用户名和密码、显示用户信息功能,在用户测试类中(TestSysuser),根据用户输

    #本关任务: 编写一个用户类(Sysuser),属性包括用户名.真实姓名.年龄.出生日期.密码,类方法中包含单独修改用户年龄.判断用户名和密码.显示用户信息功能,在用户测试类中(TestSysuser ...

  6. 复习Java第二个项目仿QQ聊天系统 03(两种通信类、登录以及注册功能完善) Java面试题并发编程相关知识生活【记录一个咸鱼大学生三个月的奋进生活】025

    记录一个咸鱼大学生三个月的奋进生活025 复习Java(仿QQ聊天系统03两种通信类.登录以及注册功能完善) TcpSocket类(与服务器进行通信) Server类(服务器类) TcpMessage ...

  7. linux中的ftp是什么意思,什么是linux的ftp

    vsftpd是一款在Linux发行版中最受推崇的FTP服务器程序. 特点是小巧轻快,安全易用.并且是一个完全免费开放源码的ftp软件 ftp的作用: FTP(File Transfer Protoco ...

  8. Linux 在 linux 中搭建 FTP 服务

    概述 在本篇博文中,我将会介绍如何搭建你自己的FTP服务 FTP是什么 FTP 是文件传输协议File Transfer Protocol的缩写.顾名思义,FTP用于计算机之间通过网络进行文件传输.你 ...

  9. 深入剖析微软ASP.NET Ajax中的数据绑定构架下篇之二

    四.例2-数据库绑定 现在,我们来讨论更为复杂的数据库绑定的例子.根据我们前面的讨论,我们找到了使用DataSource的典型场所:在前面的例1中,我们使用了一种内存数据来模拟有状态的web服务.但是 ...

最新文章

  1. Vmware下Centos7安装预览
  2. 英伟达对ARM、Linux开放光线追踪,SDK已就位,网友:switch也能跑光追的节奏?...
  3. 给女朋友讲ActiveMQ是啥?
  4. 微信小程序开发系列一:微信小程序的申请和开发环境的搭建 1
  5. python抓取网站乱码_如何使用Python抓取网站
  6. 深入浅出计算机组成原理03:处理器
  7. 微博爬虫 ----- 微博发布时间清洗
  8. 谈谈阿里log4j2事件:严重性是个主观判断
  9. UEditor 自定义input,复选框,弹窗,修改,删除,取值,存值
  10. win10 家庭版(20H2) 安装sqlserver2000 指南
  11. office2010每次打开都要配置进度的解决方案
  12. 【CAD技巧】120个常见CAD问题解决办法
  13. A problem has been detected and windows has been shut down to prevent damage to your computer.
  14. PassMark PerformanceTest v10.1.1004 电脑性能测试工具直装版
  15. 基金定投如何选择买卖点?——关于定投的择时研究
  16. 联想Idealpad 710s - 13IKB 重装系统教程以及遇到的问题
  17. 10个降低PCB成本的技巧!PCB采购必须掌握!
  18. 一个忙碌架构师的Java后端书架(2022)
  19. 基于arcpy开发arcgis工具
  20. java-net-php-python-jsp家具进销存管理系统1计算机毕业设计程序

热门文章

  1. 招募:500名学生,36元上16节课,报满为止,限时抢购!(含4本实体书包邮)...
  2. matlab document 改成中文,网上下载的数学建模模板为何无法编译,已经把document设置成utf8...
  3. 认识微型计算机的组成课件,认识微型计算机说课课件
  4. Android 邮箱APP体验
  5. 决策树理论--Decision tree
  6. [系统设计] 可扩展性--Scalability Harvard Web Development David Malan
  7. el-calendar 自定义我的日程
  8. 亚马逊和Epic将入驻,微软应用商城向第三方开放
  9. Python-中北大学人工智能OpenCV人脸识别(根据图片训练数据,根据训练好的数据识别人脸)
  10. ICEY攻略 论如何获得所有奖杯达成成就(没错,我就是拿CSDN写了游戏攻略)