Check if folder contains files with certain extensions

First of all your logic is reversed! ;)
here is you correct code:

        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);
        }

Although, i recommend using System.Timers.Timer class for you application!


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

This is checking if there are no files... then you are reporting "New Recording exists". I think you just have your logic the wrong way around. else is where it means you have found some files.

In addition, if you want to check for just *.wma files then you can use the GetFiles overload that takes a search pattern parameter, for example:

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

SIDE NOTE: You may be interested in the FileSystemWatcher, this would enable you to monitor your recordings folder for changes (including when files are added). This would eliminate your requirement to poll every 5 minutes, and you get near-instant execution when the file is added, as opposed to waiting for the 5 minute interval to tick over


Don't use GetFiles if you're going to throw the result away. Use an enumeration so you can exit early:

Directory.EnumerateFiles(Folder, "*.wma", SearchOption.AllDirectories).FirstOrDefault() != null

Tags:

C#