如何使用C#.net获取FTP或目录中的最新文件 [英] how to get the latest file in a FTP or directory using C#.net

查看:74
本文介绍了如何使用C#.net获取FTP或目录中的最新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人

我有一个要求,就是我必须从FTP中存在的目录中下载最新文件.
是否可以从列表中仅获取最新文件?

等待回复,


问候
Ramesh

Dear All

I have a requirement that is i have to download the latest files from the directory which is present in FTP.
Is it possible to get only the latest file from the list?

waiting for reply,


Regards
Ramesh

推荐答案

此代码之前对我有帮助...它使您可以查询FTP目录并获取与正则表达式匹配且比更新的文件列表. ``一些约会''

返回的结果按日期排序,因此您显然可以从结果中获取最新"文件


将源代码"放入您的项目&您可以使用以下内容

用法
This code has helped me before...it lets you query an FTP directory and get a list of files batch that match a regular expression and are newer than ''Some Date''

The results returned are sorted by date, so you can obviously get the ''newest'' file out of the results


Put the ''Source Code'' into your project & you can use as follows

Usage
// Your FTP site
string ftpPath = "ftp://some/localtion/to/ftp/directory/";

// Some expression to match against the files...do they have a consistent name? This example would find XML files that had 'some_string' in the file name
Regex matchExpression = new Regex("^some_string.+\.xml


",RegexOptions.IgnoreCase); // 仅大于此值的文件 DateTime cutOff = DateTime.Now.AddDays(-10); 列出< ftplineresult>结果= FTPHelper.GetFilesListSortedByDate(ftpPath,matchExpression,cutOff); </ ftplineresult >
", RegexOptions.IgnoreCase); // Only files greater than this value DateTime cutOff = DateTime.Now.AddDays(-10); List<ftplineresult> results = FTPHelper.GetFilesListSortedByDate(ftpPath, matchExpression, cutOff); </ftplineresult>



源代码



Source Code

namespace FTP.Utilities
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Text.RegularExpressions;
    public enum ListStyle
    {
        Unix,
        Windows
    }
    public class FTPLineResult
    {
        public ListStyle Style { get; set; }
        public string Name { get; set; }
        public DateTime DateTime { get; set; }
        public bool IsDirectory { get; set; }
        public long Size { get; set; }
    }
    /// <summary>
    /// from http://blogs.msdn.com/adarshk/archive/2004/09/15/230177.aspx
    /// </summary>
    public class FTPLineParser
    {
        private Regex winStyle = new Regex(@"^(?<month>\d{1,2})-(?<day>\d{1,2})-(?<year>\d{1,2})\s+(?<hour>\d{1,2}):(?<minutes>\d{1,2})(?<ampm>am|pm)\s+(?<dir>[<]dir[>])?\s+(?<size>\d+)?\s+(?<name>.*)


",RegexOptions.IgnoreCase); 公共 FTPLineResult解析(字符串行) { 匹配match = winStyle.Match(line); 如果(匹配成功) { 返回 ParseMatch(match.Groups,ListStyle.Windows); } 抛出 异常(" 无效的行格式"); } 私有 FTPLineResult ParseMatch(GroupCollection matchGroups,ListStyle样式) { 字符串 dirMatch =(style == ListStyle.Unix?" : < dir>"); FTPLineResult结果= FTPLineResult(); result.Style =样式; result.IsDirectory = matchGroups [" ].Value.Equals(dirMatch,StringComparison.InvariantCultureIgnoreCase); result.Name = matchGroups [" ].Value; result.DateTime = DateTime( 2000 + > int .Parse(matchGroups [" ].Value)," 月"].Value), int .Parse(matchGroups [" ] .Value), int .Parse(matchGroups [" ].Value)+(matchGroups [ ampm"].Value.Equals (" )&& matchGroups [" 小时"].Value!= 12"? 12 : 0 ), int . (matchGroups [" ].Value), 0 ); 如果(!res.IsDirectory) result.Size = .Parse(matchGroups [" ].Value); 返回结果; } } /// < > /// FTP类可检索与表达式和文件日期截止时间匹配的文件 /// < /summary > 公共 FTPHelper { /// < > /// 从FTP服务器中以指定的路径获取与命名匹配的文件列表正则表达式,以及谁的文件日期在截止日期之后 /// < /summary > /// < 参数 名称="ftpPath" < > /// < 参数 name ="nameRegex" < > /// < 参数 名称="cutoff" < > /// < 返回 > < > 公共 静态列表< FTPLineResult> GetFilesListSortedByDate( string ftpPath,Regex名称Regex,DateTime截止时间) { 列表< FTPLineResult>输出= 列表< FTPLineResult>(); FtpWebRequest request = FtpWebRequest.Create(ftpPath) as FtpWebRequest; ConfigureProxy(请求); request.Method = WebRequestMethods.Ftp.ListDirectoryDe​​tails; FtpWebResponse response = request.GetResponse() as FtpWebResponse; StreamReader directoryReader = StreamReader(response.GetResponseStream(),System.Text.Encoding.ASCII); var 解析器= FTPLineParser(); while (!directoryReader.EndOfStream) { var result = parser.Parse(directoryReader.ReadLine()); 如果(!result.IsDirectory&&result.DateTime > 截止& nameregex. IsMatch(result.Name)) { output.Add(结果); } } // 需要确保文件以升序排列 output.Sort( 比较< FTPLineResult>( 代理(FTPLineResult res1,FTPLineResult res2) { 返回 res1.DateTime.CompareTo(res2.DateTime); } ) ); 返回输出; } /// < > /// 设置网络代理 /// < /summary > /// < 参数 名称="request" < > 私有 静态 无效 ConfigureProxy (FtpWebRequest请求) { request.Proxy = WebRequest.GetSystemWebProxy(); request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials; } } }
", RegexOptions.IgnoreCase); public FTPLineResult Parse(string line) { Match match = winStyle.Match(line); if (match.Success) { return ParseMatch(match.Groups, ListStyle.Windows); } throw new Exception("Invalid line format"); } private FTPLineResult ParseMatch(GroupCollection matchGroups, ListStyle style) { string dirMatch = (style == ListStyle.Unix ? "d" : "<dir>"); FTPLineResult result = new FTPLineResult(); result.Style = style; result.IsDirectory = matchGroups["dir"].Value.Equals(dirMatch, StringComparison.InvariantCultureIgnoreCase); result.Name = matchGroups["name"].Value; result.DateTime = new DateTime(2000 + int.Parse(matchGroups["year"].Value), int.Parse(matchGroups["month"].Value), int.Parse(matchGroups["day"].Value), int.Parse(matchGroups["hour"].Value) + (matchGroups["ampm"].Value.Equals("PM") && matchGroups["hour"].Value != "12" ? 12 : 0), int.Parse(matchGroups["minutes"].Value), 0); if (!result.IsDirectory) result.Size = long.Parse(matchGroups["size"].Value); return result; } } /// <summary> /// FTP Class to retreieve files that match an expression and file date cutoff /// </summary> public class FTPHelper { /// <summary> /// Get a list of files from the FTP server, in a specified path, that match a naming regular expression, and who's file date is after a cutoff /// </summary> /// <param name="ftpPath">The path the to FTP location</param> /// <param name="nameRegex">Regurlar expression to match when finding files</param> /// <param name="cutoff">A datetime that files on the FP server must be greater than</param> /// <returns></returns> public static List<FTPLineResult> GetFilesListSortedByDate(string ftpPath, Regex nameRegex, DateTime cutoff) { List<FTPLineResult> output = new List<FTPLineResult>(); FtpWebRequest request = FtpWebRequest.Create(ftpPath) as FtpWebRequest; ConfigureProxy(request); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; FtpWebResponse response = request.GetResponse() as FtpWebResponse; StreamReader directoryReader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII); var parser = new FTPLineParser(); while (!directoryReader.EndOfStream) { var result = parser.Parse(directoryReader.ReadLine()); if (!result.IsDirectory && result.DateTime > cutoff && nameRegex.IsMatch(result.Name)) { output.Add(result); } } // need to ensure the files are sorted in ascending date order output.Sort( new Comparison<FTPLineResult>( delegate(FTPLineResult res1, FTPLineResult res2) { return res1.DateTime.CompareTo(res2.DateTime); } ) ); return output; } /// <summary> /// set up the web proxy /// </summary> /// <param name="request"></param> private static void ConfigureProxy(FtpWebRequest request) { request.Proxy = WebRequest.GetSystemWebProxy(); request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials; } } }


这篇关于如何使用C#.net获取FTP或目录中的最新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆