I'm looking for a short bit of sample code which uses the System.Net.FtpWebRequest
namespace to get the timestamp of a specified remote file on an FTP server. I know I need to set the Method
property of my request object to WebRequestMethods.Ftp.GetDateTimestamp
but I'm not sure how to get the response back into a System.DateTime
object.
Asked
Active
Viewed 2.0k times
9

Martin Prikryl
- 188,800
- 56
- 490
- 992

Dav Evans
- 4,031
- 7
- 41
- 60
-
See also [Download files from FTP if they are created within the last hour](https://stackoverflow.com/q/10121911/850848). – Martin Prikryl Sep 22 '22 at 09:22
3 Answers
17
Yep - thats pretty much what I ended up with. I went with something like this
request = FtpWebRequest.Create("ftp://ftp.whatever.com/somefile.txt");
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
request.Proxy = null;
using (FtpWebResponse resp = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(resp.LastModified);
}
-
2One problem with this approach - it automatically converts the time to the client's current time zone, not the server's time zone. I found that I needed to use WebRequestMethods.Ftp.ListDirectoryDetails and parse the time out of the line that the file is found on in order to get the modified date of the server's time zone. – NightOwl888 Nov 30 '12 at 17:21
1
Something like this:
DateTime DateValue;
FtpWebRequest Request = (FtpWebRequest)WebRequest.Create(yourUri);
Request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
Request.UseBinary = false;
using (FtpWebResponse Response = (FtpWebResponse)Request.GetResponse())
using (TextReader Reader = new StringReader(Response.StatusDescription))
{
string DateString = Reader.ReadLine().Substring(4);
DateValue = DateTime.ParseExact(DateString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture.DateTimeFormat);
}
1
To get the date field only but not the time, do exactly as the first answer in this thread with the following exception:
Console.WriteLine(response.LastModified().ToShortDateString);

shanethehat
- 15,460
- 11
- 57
- 87

Carlos Morales
- 19
- 1