首页 > 解决方案 > 在 C# 中根据日期时间获取 FTP 文件详细信息

问题描述

问题:我想根据某个特定的日期时间从 FTP 服务器获取文件详细信息,而不使用任何 3rd 方。

问题:我的 FTP 服务器包含 1000 多个文件,因此获取所有文件并在过滤之后需要时间。

有没有更快的方法来做到这一点?

string ftpPath = "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 

Regex matchExpression = new Regex("^test.+\.xml$", RegexOptions.IgnoreCase);

// DateFilter
DateTime cutOff = DateTime.Now.AddDays(-10);

List<ftplineresult> results = FTPHelper.GetFilesListSortedByDate(ftpPath, matchExpression, cutOff);
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;
}

标签: c#.netftpftpwebrequestftpwebresponse

解决方案


问题:我的 FTP 服务器包含 1000 多个文件,因此获取所有文件并在过滤之后需要时间。

有没有更快的方法来做到这一点?

没有


唯一的标准 FTP API 是LIST命令及其伙伴。所有这些都将为您提供文件夹中所有文件的列表。没有 FTP API 可以为您提供按时间戳过滤的文件。

一些服务器支持命令中的非标准文件掩码LIST
因此,它们将允许您仅返回*.xml文件。
请参阅如何使用 FTP 基于模式匹配获取文件列表?


类似的问题:


推荐阅读