TransWikia.com

checking if file exists in FileInfo[]

Stack Overflow Asked by Abhilash VG on December 25, 2021

I am creating a Windows application in which on a button click it will check a folder specified in the .config file for ‘.SQL’ files and if it has any files then the application will execute the SQL file in the specified DB.
So for checking the ‘.sql’ file in a directory I used the below code:

DirectoryInfo d = new DirectoryInfo(path);
FileInfo[] sqlfiles = d.GetFiles("*.sql");

Now, I want to add an IF condition to check any such file exist, if not I want to place a warning message.
So could you please help me to find how to check whether any such ‘.sql’ file exist in that directory using the above code?

One Answer

You can use .Any() to check if any array, or list, or IEnumerable has items. IMO it's a much clearer intent than list.Count > 0.

DirectoryInfo d = new DirectoryInfo(path);
FileInfo[] sqlfiles = d.GetFiles("*.sql");
if(sqlFiles.Any())
{
   // At least one .sql file exists
}
else
{
    // No sql files exist
}

(Cue arguments about iterators etc.)

Answered by Neil on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP