c# - FileSystemWatcher 监控目录大小

标签 c# windows-services filesystemwatcher

您好,我正在创建一个 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;
        }

最佳答案

您正在使用 FileSystemEventArgs 提供的文件夹路径,因此这将是已更改的文件夹。相反,为您正在监视的每个目录根创建一个对象,并在其中存储根路径并使用它来代替 EventArgs

您可能会发现创建此对象的一种简单方法就是使用事件处理程序的 lambda 函数,如下所示。这有效地将外部范围的路径包装到您正在监视的每个路径的不同对象中。

 FileSystemWatcher watcher = new FileSystemWatcher();
 watcher.Path = dirPaths[i].ToString();
 watcher.NotifyFilter = NotifyFilters.Size;
 watcher.EnableRaisingEvents = true;
 watcher.Changed += delegate (object source, FileSystemEventArgs e)
 {
    float dirSize = CalculateFolderSize(watcher.Path); // using the path from the outer scope

    float limitSize = int.Parse(_config.TargetSize);//getting the limit size 

    if (dirSize > limitSize)
    {
        eventLogCheck.WriteEntry("the folloing path has crossed the limit " + directory);
        //TODO: mail sending
    }
 };

关于c# - FileSystemWatcher 监控目录大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10347283/

相关文章:

c# - WPF设计问题

networking - Net.exe在使用/savecred时使用 'Error: A command was used with conflicting switches.'

cocoa - 在沙盒应用程序中使用 FSEvents

c# - 从 Windows 服务中建立 SSL 连接时出现异常

c++ - Windows服务在C++中以一定的时间间隔运行一个方法

vb.net - 在 FileSystemWatcher 中处理多个更改事件

.net - System.IO.FileSystemWatcher 的底层是如何工作的?

c# - Unity - 如何让游戏对象在碰到两个碰撞器时只发生一次碰撞

c# - 使用带有 XML post 的 HttpWebRequest 时如何添加 Bearer 和 Scope

C# 创建函数队列