使用 C# 从 FTP 服务器下载文件到修改日期大于指定的本地文件夹

Download files from FTP server in C# to local folder with modification date greater than specified

我在 C# Web 应用程序上工作,需要使用 FTP 将文件下载到本地文件夹。这些图像的修改日期必须大于我指定的日期。

代码:

public static List<FTPLineResult> GetFilesListSortedByDate(string ftpPath, Regex nameRegex, DateTime cutoff, System.Security.Cryptography.X509Certificates.X509Certificate cert)
{
    List<FTPLineResult> output = new List<FTPLineResult>();

    if (cert != null)
    {
        FtpWebRequest request = FtpWebRequest.Create(ftpPath) as FtpWebRequest;
        request.Credentials = new NetworkCredential("unm", "pwd");
        request.ClientCertificates.Add(cert);

        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;
}

我必须使用证书 (.p12)。
我该怎么做?

您必须将远程文件的时间戳检索到您想要的select。

不幸的是,由于 .NET 框架不支持 FTP MLSD 命令,因此没有真正可靠和有效的方法来使用 .NET 框架提供的功能检索时间戳。 MLSD 命令以标准化的机器可读格式提供远程目录列表。命令和格式由 RFC 3659.

标准化

.NET 框架支持的您可以使用的替代方案:

  • ListDirectoryDetails method(FTP LIST 命令)检索目录中所有文件的详细信息,然后处理 FTP 服务器特定详情格式

    *nix 格式:Parsing FtpWebRequest ListDirectoryDetails line DOS/Windows格式:C# class to parse WebRequestMethods.Ftp.ListDirectoryDetails FTP response

  • GetDateTimestamp method (FTP MDTM command) to individually retrieve timestamps for each file. Advantage is that the response is standardized by RFC 3659YYYYMMDDHHMMSS[.sss]。缺点是你必须为每个文件发送一个单独的请求,效率很低。

    const string uri = "ftp://example.com/remote/path/file.txt";
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
    request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    Console.WriteLine("{0} {1}", uri, response.LastModified);
    

或者,您可以使用第 3 方 FTP 支持现代 MLSD 命令的客户端实现,或者可以在给定时间限制的情况下直接下载文件。

例如WinSCP .NET assembly supports both MLSD and time constraints.

甚至还有一个针对您的特定任务的示例:How do I transfer new/modified files only?
该示例适用于 PowerShell,但很容易转换为 C#:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "ftp.example.com",
    UserName = "username",
    Password = "password",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Download files created in 2017-06-15 and later
    TransferOptions transferOptions = new TransferOptions();
    transferOptions.FileMask = "*>=2017-06-15";
    session.GetFiles(
        "/remote/path/*", @"C:\local\path\", false, transferOptions).Check();
}

虽然对于 web 应用程序,WinSCP 可能不是最好的解决方案。您也许可以找到另一个具有类似功能的第三方库。


WinSCP 还支持使用客户端证书进行身份验证。参见 SessionOptions.TlsClientCertificatePath。但这真的是一个单独的问题。

(我是WinSCP的作者)