17

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!

ihorko
  • 6,855
  • 25
  • 77
  • 116

7 Answers7

30

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.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • DirectoryInfo and EnumerateFiles is also much faster if the directory is a UNC path over the network: https://social.msdn.microsoft.com/Forums/vstudio/en-US/9cf1ef93-6931-4e90-bb87-28569767fad3/systemiofilegetlastwritetime-takes-a-very-long-time-to-return-results?forum=csharpgeneral – Matthew Lock Jan 15 '15 at 00:28
  • I'm getting an error with EnumerateFiles().Select where it does't contain a definition for select? is that specific .NET version? – 0x2bad Jun 19 '17 at 15:43
  • @YA If you're not pulling in the namespace `System.Linq`, you won't see the Linq extension methods. https://msdn.microsoft.com/en-us/library/system.linq(v=vs.110).aspx – Nicholas Carey Jun 23 '17 at 20:00
  • your probably not going to have much luck with that unless you also include only the date component of today in the equality check there.. ah I see you've done so – nrjohnstone Aug 20 '17 at 18:06
  • @NicholasCarey Why do you include the `.LastWriteTime` in the `.Where` part? The OP asked about the 'created time have today'. I'm missing something? – PeterCo Mar 24 '18 at 11:32
  • Because, barring somebody fiddling with the file attributes, `FileInfo.CreationTime` is the date/time at which the file was actually *created*; `FileInfo.LastUpdateTime` is the date/time the *last write* (e.g. the last *update*) to the file occurred. Once the file is created, it's creation time doesn't change, even if the file is reopened and *modified*. However, it's `LastUpdateTime` does change. This ensures that it picks up files created or modified on the current day. And in my experience, you're generally interested in both of those. – Nicholas Carey Mar 27 '18 at 19:47
29

Try this:

var todayFiles = Directory.GetFiles("path_to_directory")
                 .Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.Date);
kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
3

You need to get the directoryinfo for the file

public List<String> getTodaysFiles(String folderPath)
{
    List<String> todaysFiles = new List<String>();
    foreach (String file in Directory.GetFiles(folderPath))
    {
        DirectoryInfo di = new DirectoryInfo(file);
        if (di.CreationTime.ToShortDateString().Equals(DateTime.Now.ToShortDateString()))
            todaysFiles.Add(file);
    }
    return todaysFiles;
}
Sorceri
  • 7,870
  • 1
  • 29
  • 38
  • I would recommend using `FileInfo` and `Date.Today`, but thanks for pointing me the right way to go without LINQ – Breeze Nov 10 '16 at 15:08
  • Nicely done, but you could also use the "CreationTime.Date" member to compare the file's date to DateTime.Today, rather than converting each date into strings. – Mike Gledhill Jul 26 '17 at 08:29
1

You could use this code:

var directory = new DirectoryInfo("C:\\MyDirectory");
var myFile = (from f in directory.GetFiles()
             orderby f.LastWriteTime descending
             select f).First();

// or...
var myFile = directory.GetFiles()
             .OrderByDescending(f => f.LastWriteTime)
             .First();

see here: How to find the most recent file in a directory using .NET, and without looping?

Community
  • 1
  • 1
MUG4N
  • 19,377
  • 11
  • 56
  • 83
0

using System.Linq;

DirectoryInfo info = new DirectoryInfo("");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
    // DO Something...
}

if you wanted to break it down to a specific date you could try this using a filter

var files = from c in directoryInfo.GetFiles() 
            where c.CreationTime >dateFilter
            select c;
MethodMan
  • 18,625
  • 6
  • 34
  • 52
0

You should be able to get through this:

var loc = new DirectoryInfo("C:\\");


var fileList = loc.GetFiles().Where(x => x.CreationTime.ToString("dd/MM/yyyy") == currentDate);
foreach (FileInfo fileItem in fileList)
{
    //Process the file
}
Abdel Raoof Olakara
  • 19,223
  • 11
  • 88
  • 133
0
var directory = new DirectoryInfo(Path.GetDirectoryName(@"--DIR Path--"));
DateTime from_date = DateTime.Now.AddDays(-5);
DateTime to_date = DateTime.Now.AddDays(5);

//For Today 
var filesLst = directory.GetFiles().AsEnumerable()
              .Where(file.CreationTime.Date == DateTime.Now.Date ).ToArray(); 

//For date range + specific file extension 
var filesLst = directory.GetFiles().AsEnumerable()
              .Where(file => file.CreationTime.Date >= from_date.Date && file.CreationTime.Date <= to_date.Date && file.Extension == ".txt").ToArray(); 

//To get ReadOnly files from directory  
var filesLst = directory.GetFiles().AsEnumerable()
              .Where(file => file.IsReadOnly == true).ToArray(); 

//To get files based on it's size
int fileSizeInKB = 100; 
var filesLst = directory.GetFiles().AsEnumerable()
              .Where(file => (file.Length)/1024 > fileSizeInKB).ToArray(); 
Access Denied
  • 886
  • 1
  • 13
  • 24