2012-11-29 38 views
1

我正在寫一個程序有點麻煩。該程序會檢查遠程ftp站點上的文件創建日期,如果它與今天的日期匹配,它將下載文件並將其上傳到另一個ftp站點。我收到以下錯誤,當我運行程序:問題與FtpWebRequest getDateTimestamp和DateTime

未處理的異常system.formatexception字符串未被識別爲有效的datetime

這裏是我使用創建日期FTP文件轉換爲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); 

任何想法,我在做什麼錯在這裏?

+0

有什麼'fileDateTime'字符串的內容? –

+0

它應該是在ftp服務器上創建文件的日期。如果有幫助,我可以爲該行所指的類添加代碼。 –

+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"); 
+0

我試着添加,仍然有相同的錯誤。我在Console.WriteLine(fileDateTime)之後評論了所有內容;只是爲了看看輸出是什麼,它是空白的。所以我猜測沒有什麼東西扔進fileDateTime字符串,所以沒有什麼可以解析DateTime的。不確定最佳的行動方式在這裏。 –

+0

如果它返回一個空字符串,那麼該文件不存在,或者存在'DownloadftpClient'的錯誤。 –

+0

我很確定程序中有一個錯誤。我對我認爲的問題有一個粗略的想法,但我不完全確定。 –