1

How can i check there are no xls found in the directory? I tried the code below, but it doesn't work...

if (!System.IO.File.Exists(".xls"))
{
   MessageBox.Show("No XLS dile found");
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Nerdynosaur
  • 1,798
  • 9
  • 32
  • 61
  • ***Duplicate question was 4 years old.*** Jon Skeet answers with new Directory.EnumerateFiles method. – Win Aug 13 '13 at 14:19

5 Answers5

10

Currently you're looking for a single file called .xls. You should instead use Directory.EnumerateFiles:

if (!Directory.EnumerateFiles(directory, "*.xls").Any())
{
    ...
}

Or if you're going to want the files anyway, use Directory.GetFiles:

string[] files = Directory.GetFiles(directory, "*.xls");
if (files.Length == 0)
{
    ...
}
else
{
    // Handle the files
}

(Note that EnumerateFiles was introduced in .NET 4; you can use GetFiles in both cases of course, it's just cleaner to use EnumerateFiles when you can.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Try This

            if (!System.IO.Directory.GetFiles("C:\\path", "*.xls", SearchOption.AllDirectories).Any())
        {
            MessageBox.Show("No XLS dile found");
        }
Michou2000
  • 21
  • 2
1

Try:

if (!Directory.EnumerateFiles(path, "*.xls").Any()) { ... }
Alessandro D'Andria
  • 8,663
  • 2
  • 36
  • 32
1

This will do

if (!System.IO.Directory.GetFiles("C:\\Users\\admin\\Desktop", "*.xls", System.IO.SearchOption.AllDirectories).Any())
{
    Console.WriteLine("*.xls files not found");
}
else
{
    Console.Write("*.xls files exist");
}
0

Maybe it's not perfect, but simple :)

var files = Directory.GetFiles(directory);
if(!files.Any(x=>x.EndsWith(".xls")))
{
   MessageBox.Show("No XLS dile found");
}
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105