我正在计算指定目录其中包含大量数据中最近一次写入时间早于10分钟的所有文件的总大小。这是我在下面尝试过的代码:
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";
这在我指定local路径时有效,但是在指定网络路径时会抛出< IOException。为什么会发生?有没有一种方法可以让我“持有”网络路径或确保与该路径的连接不会失败?
DirectoryInfo.EnumerateFiles()
和DirectoryInfo.EnumerateDirectories
是最佳选择。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
}
}
}