首页 > 解决方案 > 如何从我正在跟踪文件大小的目录中获取子目录名称以使用 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;
        }

    }
}

标签: c#.netdirectoryinfo

解决方案


DirectoryInfo 类没有任何文件夹大小的概念。我认为您最好的选择是遍历每个子目录(可能是递归的)并将其中文件的大小相加。


推荐阅读