I'm trying to calculate the total size of all the files in which last write time is earlier than 10 minutes from now in a specified directory which has a large amount of data. Here goes the code I've tried below:
DateTime from_date = DateTime.Now.AddMinutes(-10);
List<string> list = Directory.GetFiles(@[PATH], "*", SearchOption.AllDirectories)
.Where(x => File.GetLastWriteTime(x).Date > from_date)
.Select(x => new FileInfo(x).FullName)
.ToList();
foreach (String s in list)
{
FileInfo file = new FileInfo(s);
size += file.Length;
}
button6.Text = ((size / 1024f) / 1024f) + "MB";
This works when I specify a local path, but throws me a Network name no longer available IOException when specifying a network path. Why does it happen? Is there a way where I can kind of "hold" the network path or make sure the connection to this path will not fail?
DirectoryInfo.EnumerateFiles()
and DirectoryInfo.EnumerateDirectories
are the best option.
var directories = new DirectoryInfo(root).EnumerateDirectories().OrderByDescending(d => d.Name);
IEnumerable<FileInfo> files;
foreach (DirectoryInfo directoryInfo in directories)
{
files = directoryInfo
.EnumerateFiles("*" + extension, SearchOption.AllDirectories)
.OrderByDescending(f => f.LastWriteTime);
foreach (FileInfo f in files)
{
if ((f.LastWriteTime.CompareTo(DateTime.Now.AddMinutes(-10)) == 1)
{
// Do whatever you want with the files
}
}
}