c# - 如何从我正在跟踪文件大小的目录中获取子目录名称以使用 DirectoryInfo?
问题描述
我有一个为批处理创建的简单类,但我无法解决这个问题。我正在使用 DirectoryInfo 标记任何超过 4KB 的文件并发送警报电子邮件。这适用于我正在监视的目录中的文件,但不适用于目录中的文件夹。如果我正在监视的目录中有一个文件夹,我会得到一个 FileInfo() 的列表,而不是子目录本身的名称。所以我要问的是,我如何实际监控子目录的大小而不是其中的文件?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Hana.BusinessLogicLayer
{
internal class FileMonitor
{
public static bool Process()
{
var filewatch = new DirectoryInfo(@"C:\Users\me\Desktop\Test");
List<string> largeFiles = new List<string>();
bool foundfile = false;
foreach (var f in filewatch.GetFiles("*", SearchOption.AllDirectories))
{
var theSize = f.Length / 1000;
if (theSize > 4) && f.LastWriteTime > DateTime.Now.AddMinutes(-15))
{
Console.WriteLine("NEW LARGE FILE WRITTEN: {0} is {1}KB.", f.Name, theSize);
largeFiles.Add(f.Name);
foundfile = true;
}
else
{
Console.WriteLine("SMALL FILE: {0} is small and does not matter", f.Name);
}
if (foundfile)
{
var sendMail = Utility.SMTPUtil.SendMailCustom(initiatingUserId: 1,
toAddresses: new List<string> { "email@email.com" },
subject: "File Manager Test",
bcc: new List<string> { "email@email.com" },
body: f.Name + " is " + theSize + "KB and the last
write time was " + f.LastWriteTime
);
Console.WriteLine("Email about large file sent");
Console.WriteLine(DateTime.Now.ToLocalTime());
if (!sendMail.Success)
{
return false;
}
}
}
Console.WriteLine("Press any key to continue . . .");
Console.ReadLine();
return true;
}
}
}
解决方案
DirectoryInfo 类没有任何文件夹大小的概念。我认为您最好的选择是遍历每个子目录(可能是递归的)并将其中文件的大小相加。
推荐阅读
- python - 在条件语句中使用时间作为参数
- visual-studio-code - 无法使用 html 文件将样式应用于 VSCode Webview
- ubuntu - Meteor Svelte 找不到我在 Ubuntu 上创建的文件
- ubuntu - 如何使用 udev 规则自动挂载 USB 块设备?
- travis-ci - 在 GitHub 操作上使用 dpl
- java - 三星键盘退格键不适用于 SearchView
- php - 如何以智能的方式使用 PHP PDO 显示来自 PostgreSQL 的图像
- java - 尽管是数学,但代码打印你好世界
- apache-spark - 在 k8s 集群中 Spark 提交失败
- java - Spring将实体管理器getResultList结果转换为JSON