iT邦幫忙

0

C# 抓取指定時間的檔案

  • 分享至 

  • xImage

我想要只抓取今天更新或者創建的檔案(今天最舊的檔案),可是如果沒有今天的檔案,會直接錯誤。

我想要改成如果今天沒有,就改成昨天的,或者更舊的資料。

下面是我目前的程式碼,不知道如何修改

        DateTime today = DateTime.Now.Date;
        
  DirectoryInfo di = new DirectoryInfo(@"C:\Users\Desktop\ME");
       
var Wfile = (from f in di.GetFiles("W*.xlsx").
Where(f => f.LastWriteTime == today || f.CreationTime.Date == today) 
orderby f.LastWriteTime descending select f).Last();
看更多先前的討論...收起先前的討論...
powerc iT邦新手 1 級 ‧ 2021-06-01 16:19:43 檢舉
把where拿掉
powerc iT邦新手 1 級 ‧ 2021-06-01 16:23:27 檢舉
然後你排序desc應該要取first(最新)的吧?
Where 條件是今天的,我是想要今天的,然後最舊的,也就是第一個檔案。才這樣寫
如果是 First,我也不用設條件了。
所以想要一個判斷,今天的第一個檔案,如果沒有,只能讀取昨天的。是有試過,如果需要我之前的判斷,我明天會再打上來。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
japhenchen
iT邦超人 1 級 ‧ 2021-06-02 09:00:00
最佳解答

LAMBDA跟LINQ可以不要混用嗎?你的 f 分不清了,我修改如下,可以明確用.Date來比對是否為當天

DateTime today = DateTime.Now.Date;
DirectoryInfo di = new DirectoryInfo(@"C:\Users\DESKTOP\Me");
var Wfile = di.GetFiles("*.xlsx")
    .Where(f => f.Name.ToLower().StartsWith("w") && (f.LastWriteTime.Date <= today.Date)
    .OrderBy(o => o.LastWriteTime)
    .FirstOrDefault();
if(Wfile!=null)
    Console.WriteLine(Wfile);

如果沒有修改過,LastWriteTime必定等於CreationTime
修改過,LastWriteTime必定大於CreationTime

所以排序以lastWriteTime即可

0
海綿寶寶
iT邦大神 1 級 ‧ 2021-06-01 16:46:50

f.LastWriteTime == today || f.CreationTime.Date == today改成
f.LastWriteTime <= today || f.CreationTime.Date <= today試試看

0
小魚
iT邦大師 1 級 ‧ 2021-06-01 19:14:19

因為你用了Last,
如果改成LastOrDefault呢?

我要發表回答

立即登入回答