您好我正在创建一个 Windows 服务来监视某些目录,以查看目录的大小是否已达到其限制。我创建了一个文件系统观察程序,如下所示:
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = dirPaths[i].ToString();
watcher.NotifyFilter = NotifyFilters.Size;
watcher.EnableRaisingEvents = true;
watcher.Changed += new FileSystemEventHandler(OnChanged);
和
private void OnChanged(object source, FileSystemEventArgs e)
{
try
{
string directory = new DirectoryInfo(e.FullPath).Parent.FullName;//gettting the directory path from the full path
float dirSize = CalculateFolderSize(directory);
float limitSize = int.Parse(_config.TargetSize);//getting the limit size
if (dirSize > limitSize)
{
eventLogCheck.WriteEntry("the following path has crossed the limit " + directory);
//TODO: mail sending
}
}
catch (Exception ex)
{
eventLogCheck.WriteEntry(ex.ToString());
}
}
CalculateFolderSize
检查驱动器中所有文件和子目录的大小。
现在,当我将文件添加到目录(例如 .xls、.txt 等文件)时,这可以正常工作,但是如果我将文件夹添加到目录,它不会触发OnChanged
事件?
如果我启用:
watcher.IncludeSubdirectories = true;
它确实触发了Onchanged
事件,但在这种情况下,它只检查子目录而不是整个目录。
请有人告诉我如何使它工作,以便当我将文件夹复制到正在监视的目录时,它会触发Onchanged
事件并计算目录的新大小。
如果这有帮助,我的CalculateFolderSize
功能如下:
//function to calculate the size of the given path
private float CalculateFolderSize(string folder)
{
float folderSize = 0.0f;
try
{
//Checks if the path is valid or not
if (!Directory.Exists(folder))
{
return folderSize;
}
else
{
try
{
foreach (string file in Directory.GetFiles(folder))
{
if (File.Exists(file))
{
FileInfo finfo = new FileInfo(file);
folderSize += finfo.Length;
}
}
foreach (string dir in Directory.GetDirectories(folder))
{
folderSize += CalculateFolderSize(dir);
}
}
catch (NotSupportedException ex)
{
eventLogCheck.WriteEntry(ex.ToString());
}
}
}
catch (UnauthorizedAccessException ex)
{
eventLogCheck.WriteEntry(ex.ToString());
}
return folderSize;
}