![](/img/trans.png)
[英]System.Net.FtpWebRequest GetDateTimestamp call dies
[英]Issue with FtpWebRequest getDateTimestamp and DateTime
我正在编写一个程序,我遇到了一些麻烦。 该程序检查远程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);
关于我在这里做错了什么的想法?
如果从服务器返回的字符串是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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.