2017-06-20 33 views
1

我使用C#Web应用程序,并需要使用FTP将文件下载到本地文件夹。这些图像需要修改日期大于我指定的日期。将文件从C#中的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)。
我该怎么做?

回答

2

你必须检索远程文件的时间戳来选择你想要的。

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

替代品,你可以使用,这是由.NET框架的支持:


另外,您可以使用支持现代MLSD命令第三方FTP客户端实现,或者可以直接下载给定的时间约束文件。

例如WinSCP .NET assembly支持MLSDtime 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的作者)

+0

感谢马丁,我更新我的帖子的代码我用来检索文件列表。我可以在while块中下载文件,而不是执行** output.Add(result); **我可以像**下载(destnationfilename,sourcefilename)**那样做一些事情吗? – dragy

+0

当然可以。但是,如果这是您所期望的,我认为这不会对性能有很大帮助。 –

+0

我以为我可以通过while循环传递相同的文件。在这种情况下,不需要通过过滤列表。但是,我不知道如何在现有的while循环中下载文件,并且使用另一个通过创建的列表来完成它。 – dragy

相关问题