【问题标题】:Issue with FtpWebRequest getDateTimestamp and DateTimeFtpWebRequest getDateTimestamp 和 DateTime 的问题
【发布时间】:2012-11-29 14:41:21
【问题描述】:

我正在编写的程序有点问题。该程序检查远程 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);

关于我在这里做错了什么有什么想法吗?

【问题讨论】:

  • fileDateTime 字符串的内容是什么?
  • 它应该是文件在 ftp 服务器上创建的日期。如果有帮助,我可以为该行引用的类添加代码。
  • 是的,但是字符串的实际内容是什么?如果没有内容样本,很难看出您需要做什么来解析它。
  • 该字符串的内容应该是 DownloadftpClient.getFileCreatedDateTime 的结果。也许我在获取 ftp 服务器上文件的时间戳和将结果转换成字符串之间跳过了一步?
  • 好的,我知道内容来自哪里,但是什么是内容?请张贴样品! :)

标签: c# datetime ftpwebrequest


【解决方案1】:

如果服务器返回的字符串是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");

【讨论】:

  • 我尝试添加它,但仍然遇到同样的错误。我在 Console.WriteLine(fileDateTime); 之后注释掉了所有内容。只是看看输出是什么并且它是空白的。所以我猜测没有任何东西被扔到 fileDateTime 字符串中,因此 DateTime 没有任何东西可以解析。不确定这里的最佳行动方案是什么。
  • 如果它返回一个空字符串,那么要么文件不存在,要么DownloadftpClient 存在错误。
  • 我很确定程序中存在错误。我对我认为问题出在哪里有一个粗略的想法,但我并不完全确定。
  • 贴出所有代码并寻求帮助以找到错误会不合时宜吗?
  • 是您自己开发的吗?我能找到的最接近的版本是 metastruct 在 8 月发布的 CodeProject 文章:codeproject.com/Tips/443588/Simple-Csharp-FTP-Class
猜你喜欢
  • 1970-01-01
  • 2011-11-06
  • 2010-11-05
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多