Directory.GetFiles get today's files only

前端 未结 7 642
青春惊慌失措
青春惊慌失措 2021-01-04 01:02

There is nice function in .NET Directory.GetFiles, it\'s simple to use it when I need to get all files from directory.

Directory.GetFiles(\"c:\\\\Files\")
<         


        
7条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 01:43

    For performance, especially if the directory search is likely to be large, the use of Directory.EnumerateFiles(), which lazily enumerates over the search path, is preferable to Directory.GetFiles(), which eagerly enumerates over the search path, collecting all matches before filtering any:

    DateTime today = DateTime.Now.Date ;
    FileInfo[] todaysFiles = new DirectoryInfo(@"c:\foo\bar")
                             .EnumerateFiles()
                             .Select( x => {
                                x.Refresh();
                                return x;
                             })
                             .Where( x => x.CreationTime.Date == today || x.LastWriteTime == today )
                             .ToArray()
                             ;
    

    Note that the the properties of FileSystemInfo and its subtypes can be (and are) cached, so they do not necessarily reflect current reality on the ground. Hence, the call to Refresh() to ensure the data is correct.

提交回复
热议问题