我正在编写一个正在编写程序的麻烦。该程序检查远程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);
关于我在这里做错了什么想法?
答案 0 :(得分: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;
}
(在this answer的帮助下。)
然后调用代码变为:
DateTime lastModified = DownloadftpClient.getFileCreatedDateTime("test.txt");