2016-04-26 24 views
-1

我試圖從某個目錄中獲取最近的文件,該目錄也具有某個前綴。如果我沒有在getfiles()後面加入搜索字符串,我能夠成功使用代碼,但是如果確實使用它,我會得到一個異常:獲取帶有某個前綴的最新文件

'System .InvalidOperationException」有 發生在System.Core.dll

FileInfo mostrecentlog = (from f in logDirectory.GetFiles("Receive") orderby f.LastWriteTime descending select f).First(); 
+0

InvalidOperationException的消息說什麼?它沒有記錄,但也許不喜歡沒有通配符的搜索模式。對於你想要的前綴'「接收*」' –

+0

你的搜索模式是什麼?你真的應該顯示那些不起作用的代碼,而不是那些有用的代碼。 – juharr

+0

你應該可以簡單地在你的linq中添加一個where條件來搜索特定的文件,或者如果你願意的話,簡單地拉回整個列表並重復遍歷它們(我個人推薦這兩個建議中的第一個)。 – user2366842

回答

1

那麼,你需要問幾個問題給自己。

如果什麼也沒有匹配的文件?你目前的實施工作是否正常沒有。它會崩潰。爲什麼?因爲.First()運算符。

正如你提到的,要找到某些前綴的文件,所以加通配符*你的前綴。查找以某些前綴開頭的所有文件。

FileInfo mostrecentlog = (from f in logDirectory.GetFiles("your_pattern*") orderby 
             f.LastWriteTime descending select f).FirstOrDefault(); 

現在檢查mostrecentlog不爲空,如果它不是null,則它會包含最新的文件符合特定的前綴。

+0

這個工作。對不起,我完全忘了將它標記爲通配符。謝謝! – user3494110

1

使用方法的語法可能會使這個閱讀與Where()條款沿着更容易一點,以指定要搜索的內容:

// You must specify the path you want to search ({your-path}) when using the GetFiles() 
// method. 
var mostRecentFile = logDirectory.GetFiles("{your-path}") 
           .Where(f => f.Name.StartsWith("Receive")) 
           .OrderByDescending(f => f.LastWriteTime) 
           .FirstOrDefault(); 

同樣,你可以指定Directory.GetFiles()方法中的搜索模式作爲第二個參數:

// You can supply a path to search and a search string that includes wildcards 
// to search for files within the specified directory 
var mostRecentFile = logDirectory.GetFiles("{your-path}","Receive*") 
           .OrderByDescending(f => f.LastWriteTime) 
           .FirstOrDefault(); 

記住FirstOrDefault()將返回找到或null如果沒有產品找到的第一個元素是很重要的,所以你需要進行檢查,以確保你發現了一些之前繼續:

// Get your most recent file 
var mostRecentFile = DoTheThingAbove(); 
if(mostRecentFile != null) 
{ 
     // A file was found, do your thing. 
} 
0

只需使用FirstOrDefault(),而不是First()

FileInfo mostrecentlog = (from f in logDirectory.GetFiles("Receive") orderby f.LastWriteTime descending select f).FirstOrDefault() 
+0

記住,根據其他答案,使用'FirstOrDefault()'實際上可能會返回一個必須處理的空值。 – user2366842

+0

當然,但它會解決他目前的異常問題。他需要再檢查值是否爲空 –

相關問題