2017-06-20 44 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

相關問題