Issue with FtpWebRequest getDateTimestamp and Date

2019-08-01 23:16发布

I'm having a bit of trouble with a program that I'm writing. The program checks the date created of a file on a remote ftp site, then if it matched today's date it will download the file the upload it to another ftp site. I get the following error when I run the program:

unhandled exception system.formatexception string was not recognized as a valid datetime

Here is the code I'm using to convert the ftp file created date to a datetime

/* Get the Date/Time a File was Created */
string fileDateTime = DownloadftpClient.getFileCreatedDateTime("test.txt");
Console.WriteLine(fileDateTime);
DateTime dateFromString = DateTime.Parse(fileDateTime, System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat);
Console.WriteLine(dateFromString);

Any ideas on what I'm doing wrong here?

1条回答
混吃等死
2楼-- · 2019-08-01 23:55

If the string returned from the sever is 20121128194042, then your code needs to be:

DateTime dateFromString = DateTime.ParseExact(fileDateTime, 
   "yyyyMMddHHmmss", // Specify the exact date/time format received
   System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat);

EDIT

The correct code for the getFileCreatedDateTime method should be:

public DateTime getFileCreatedDateTime(string fileName)
{
    try
    {
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
        ftpRequest.Credentials = new NetworkCredential(user, pass);

        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;

        ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

        return ftpResponse.LastModified;
    }
    catch (Exception ex) 
    {
        // Don't like doing this, but I'll leave it here
        // to maintain compatability with the existing code:
        Console.WriteLine(ex.ToString());
    }

    return DateTime.MinValue;
}

(With help from this answer.)

The calling code then becomes:

DateTime lastModified = DownloadftpClient.getFileCreatedDateTime("test.txt");
查看更多
登录 后发表回答