检查文件夹是否包含具有特定扩展名的文

时间:2014-04-15 10:45:49

标签: c#

我有其他C#代码将通话记录文件丢弃到文件夹c:\ Recordings

每个文件的扩展名为.wma

我希望能够每隔5分钟检查一次该文件夹。如果文件夹包含以.wma结尾的文件,我想要执行一些代码。

如果文件夹中不包含扩展名为.wma的文件,我希望代码暂停5分钟,然后重新检查(无限期)。

我已经开始检查文件夹中是否包含任何文件,但是当我运行它时,它总是报告文件夹包含文件,即使它没有。

string dirPath = @"c:\recordings\";
        if (Directory.GetFiles(dirPath).Length == 0)
        {
            NewRecordingExists = true;
            Console.WriteLine("New Recording exists");
        }
        else
        {
            NewRecordingExists = false;
            Console.WriteLine("No New Recording exists");
            System.Threading.Thread.Sleep(300000);
        }

2 个答案:

答案 0 :(得分:24)

if (Directory.GetFiles(dirPath).Length == 0)

这是检查是否没有文件...然后您正在报告"New Recording exists"。我认为你的逻辑错误。 else表示您找到了一些文件。

此外,如果您只想检查*.wma个文件,则可以使用the GetFiles overload that takes a search pattern parameter,例如:

if (Directory.GetFiles(dirPath, "*.wma").Length == 0)
{
    //NO matching *.wma files
}
else
{
    //has matching *.wma files
}

SIDE NOTE :您可能对FileSystemWatcher感兴趣,这样您就可以监控录制文件夹中的更改(包括添加文件时)。这将消除您每5分钟轮询一次的要求,并且在添加文件时您会立即执行,而不是等待5分钟的时间间隔进行勾选

答案 1 :(得分:1)

首先,你的逻辑是颠倒过来的! ;)
这是你正确的代码:

        bool NewRecordingExists;
        string dirPath = @"c:\recordings\";
        string[] fileNames = Directory.GetFiles(dirPath, "*.wma", SearchOption.TopDirectoryOnly);
        if (fileNames.Length != 0)
        {
            NewRecordingExists = true;
            foreach (string fileName in fileNames)
            {
                Console.WriteLine("New Recording exists: {0}", fileName);
                /*  do you process for each file here */
            }
        }
        else
        {
            NewRecordingExists = false;
            Console.WriteLine("No New Recording exists");
            System.Threading.Thread.Sleep(300000);
        }

虽然,我建议您为应用程序使用System.Timers.Timer类!

相关问题