Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory.GetFiles get today's files only

Tags:

c#

.net

asp.net

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")

But how (what pattern) can I use to get only files that created time have today if there are a lot of files with different created time?

Thanks!

like image 658
ihorko Avatar asked Dec 13 '12 18:12

ihorko


People also ask

What does directory GetFiles return?

GetFiles(String, String, SearchOption) Returns the names of files (including their paths) that match the specified search pattern in the specified directory, using a value to determine whether to search subdirectories.

What is the use of the public function GetFiles as FileInfo()?

Public Function GetFiles As FileInfo()Returns a file list from the current directory. For complete list of properties and methods please visit Microsoft's documentation.

How do I get the filename from the file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.


2 Answers

Try this:

var todayFiles = Directory.GetFiles("path_to_directory")
                 .Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.Date);
like image 53
kmatyaszek Avatar answered Oct 06 '22 23:10

kmatyaszek


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.

like image 40
Nicholas Carey Avatar answered Oct 07 '22 00:10

Nicholas Carey