使用方法的語法可能會使這個閱讀與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.
}
InvalidOperationException的消息說什麼?它沒有記錄,但也許不喜歡沒有通配符的搜索模式。對於你想要的前綴'「接收*」' –
你的搜索模式是什麼?你真的應該顯示那些不起作用的代碼,而不是那些有用的代碼。 – juharr
你應該可以簡單地在你的linq中添加一個where條件來搜索特定的文件,或者如果你願意的話,簡單地拉回整個列表並重復遍歷它們(我個人推薦這兩個建議中的第一個)。 – user2366842