I’m using the System.Net.FtpWebRequest class and my code is as follows:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://example.com/folder");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("username", "password");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string names = reader.ReadToEnd();
reader.Close();
response.Close();
This is based off of the examples provided on MSDN but I couldn’t find anything more detailed.
I’m storing all the filenames in the folder in names but how can I now iterate through each of those and retrieve their dates? I want to retrieve the dates so I can find the newest files. Thanks.
WebRequestMethods.Ftp.ListDirectoryreturns a “short listing” of all the files in an FTP directory. This type of listing is only going to provide file names – not additional details on the file (like permissions or last modified date).Use
WebRequestMethods.Ftp.ListDirectoryDetailsinstead. This method will return a long listing of files on the FTP server. Once you’ve retrieved this list into thenamesvariable, you can split thenamesvariable into an array based on an end of line character. This will result in each array element being a file (or directory) name listing that includes the permissions, last modified date owner, etc…At this point, you can iterate over this array, examine the last modified date for each file, and decide whether to download the file.
I hope this helps!!