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

5 回答 5

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.)

于 2013-08-13T12:45:43.300 回答
2

Try This

            if (!System.IO.Directory.GetFiles("C:\\path", "*.xls", SearchOption.AllDirectories).Any())
        {
            MessageBox.Show("No XLS dile found");
        }
于 2013-08-13T12:56:27.427 回答
1

Try:

if (!Directory.EnumerateFiles(path, "*.xls").Any()) { ... }
于 2013-08-13T12:46:31.237 回答
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");
}
于 2013-08-13T13:04:01.977 回答
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");
}
于 2013-08-13T12:45:43.267 回答