Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if folder contains files with certain extensions

Tags:

c#

I have other C# code that drops a call recording file into the folder c:\Recordings

Each file has the extension of .wma

I'd like to be able to check the folder every 5 minutes. If the folder contains a file ending in .wma i'd like to execute some code.

If the folder does not contain a file with the .wma extension, i'd like the code to pause for 5 minutes and then re-check (infinitely).

i've started with the following the check if the folder has any files in it at all, but when I run it, it always reports the folder contains files, even though it does not.

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);
        }
like image 547
KraggleGrag Avatar asked Apr 15 '14 10:04

KraggleGrag


People also ask

How do I search for all files with specific extensions?

For finding a specific file type, simply use the 'type:' command, followed by the file extension. For example, you can find . docx files by searching 'type: . docx'.

How do I get a list of all file extensions?

If you add the -X option, ls will sort files by name within each extension category. For example, it will list files without extensions first (in alphanumeric order) followed by files with extensions like . 1, . bz2, .


1 Answers

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

like image 140
musefan Avatar answered Sep 21 '22 15:09

musefan