2016-11-10 68 views
1

我正試圖在單個目錄中查找具有最高日期的文件。問題是日期附加到文件名。我正在使用下面的代碼來嘗試拉出最大日期,但遇到了ParseExact的麻煩。使用ParseExact從文件名獲取日期

//Gather all of the files in the local directory 
var files = Directory.EnumerateFiles(r.getLeadLocalFile()); 
returnDateTime = files.Max(f => DateTime.ParseExact(f, "MMddyyXXXX.csv", CultureInfo.InvariantCulture)); 

我不斷收到以下錯誤:

String was not recognized as a valid DateTime. 

我可以告訴大家,文件路徑的值被傳遞,因爲「F」的值低於:

\\\\vamarnas02\\users\\meggleston\\User Files\\Leads\\110716ENH9.csv 

ENH9的值可能會因文件而異。

如何從我的文件名獲取DateTime?

+0

你有關於這些文件是如何創造了一些控制......可以添加一個'_'日期和名字,比如'110716_ENH9.csv'之間? – Hackerman

+0

難道你不能簡單地從文件名字符串的前6個字符? –

+0

我沒有文件名的控制權,我不知道如何用substring方法獲得最大日期時間。 –

回答

0

您需要在分析之前拆分日期文本。下面的代碼片段應該有所幫助。

假設變量f是文件名。

DateTime.ParseExact(f.Substring(f.LastIndexOf("\\") + 1, 6), "MMddyy", CultureInfo.InvariantCulture); 
+0

這樣做。我想我已經看了太久了。感謝您幫助像我一樣的虛擬人物。 –

+0

沒問題快樂幫 – user2818985

0

嘗試僅傳遞文件名「110716ENH9.csv」而不是文件的完整路徑。

MSDN DateTime.ParseExact Documentation

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

從您提供的是什麼,你的格式不完全匹配。

- 只傳遞文件名的前6個字符到ParseExact函數並將您的格式修改爲「MMddyy」。

+0

我已將我的代碼更改爲以下內容,但仍收到相同的錯誤: 'returnDateTime = files.Max(f => DateTime.ParseExact(Path。GetFileNameWithoutExtension(f),「MMddyyXXXX」,CultureInfo.InvariantCulture));' –

+0

日期格式中沒有通配符。你需要對文件名進行子串處理。由於您知道日期格式只需要前6個字符,因此只能將文件名的前6個字符傳遞給ParseExact函數,並將您的格式修改爲「MMddyy」。 – padotj

2

這是另一種方法。無需分開任何東西。但是一個錯誤的文件名(如你目前的做法)會毀了它:

//Gather all of the files in the local directory 
var files = new DirectoryInfo(r.getLeadLocalFile()).GetFiles("*.csv"); 
returnDateTime = files.Max(f => DateTime.ParseExact(f.Name.Substring(0, 6), "MMddyy", CultureInfo.InvariantCulture)); 
+0

打我吧。這應該是正確的答案 –

0

你真的需要在這裏使用ParseExact嗎?因爲你似乎只需要獲取Int32值並在之後進行比較。
所以另一種方法:你可以從提供的路徑中提取一些正則表達式的日期部分。例如,您可以用這一個:

\\\d{6} // 2 slashes and 6 digits. I'm not an expert in regex, but seems that this one is enough for your task. 

,又重新修整\\部分。因此,像這樣的循環:

private string ExtractDateFromFilename(string filename) { 
     var m = Regex.Match(filename, @"\\\d{6}"); 
     if (!string.IsNullOrEmpty(m.Value)) 
      return m.Value.Substring(1); 
     return ""; 
    } 
+0

如果性能很重要,我不會使用RegEx,IndexOf會產生更快的執行時間 – user2818985

+0

@ user2818985,當然你是對的,正則表達式在大字符串上比較慢(與字符串方法相比),但是如果你今後需要改變一些條件或者有一些複雜的比較邏輯。對於小字符串,而不是數百萬次的比較,它不會有明顯的差異(抱歉,沒有現在的這個樣本的證明樣本,也許會稍後添加一些)。 – 0x49D1