1

我正在编写的程序有点麻烦。该程序检查远程 ftp 站点上文件的创建日期,然后如果它与今天的日期匹配,它将下载文件并将其上传到另一个 ftp 站点。运行程序时出现以下错误:

未处理的异常 system.formatexception 字符串未被识别为有效的日期时间

这是我用来将 ftp 文件创建日期转换为日期时间的代码

/* 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);

关于我在这里做错了什么的任何想法?

4

1 回答 1

3

如果从服务器返回的字符串是20121128194042,那么您的代码需要是:

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

编辑

getFileCreatedDateTime方法的正确代码应该是:

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;
}

(在这个答案的帮助下。)

然后调用代码变为:

DateTime lastModified = DownloadftpClient.getFileCreatedDateTime("test.txt");
于 2012-11-29T15:44:04.397 回答