-3

How to check if any .txt file exists in a folder?

If the folder still have .txt file output a error messagebox.

Thx all! Actually i want to make a function can check any .txt file exists in a folder. If yes write a error message to eventLog. Final My code:

     System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
     DirectoryInfo di = new DirectoryInfo(@"c:/Users/Public/Definitions");
     FileInfo[] TXTFiles = di.GetFiles("*.txt");
     foreach (var fi in TXTFiles)
     {
         if (fi.Exists)
         {
             appLog.Source = "Definitions Folder still have text files";
             appLog.WriteEntry("Still have txt files.");
         }
     }  
Fabre
  • 253
  • 1
  • 3
  • 8
  • This question may have been asked: http://stackoverflow.com/questions/7385251/how-to-check-if-a-file-exists-in-a-folder – myselfmiqdad Dec 29 '15 at 03:19
  • 1
    The question linked is a duplicate - but its accepted answer is old, and .net offers a better solution now with EnumerateFiles. – ROX Feb 20 '17 at 16:46

3 Answers3

2

You can use the Directory.EnumerateFiles like this:

if(Directory.EnumerateFiles(folder, "*.txt",SearchOption.TopDirectoryOnly).Any())
   Foo();

See more here Directory.EnumerateFiles Method

Joel R Michaliszen
  • 4,164
  • 1
  • 21
  • 28
2

You can check like below :

DirectoryInfo dir = new DirectoryInfo(@"c:\Directory");
FileInfo[] TXTFiles = dir.GetFiles("*.txt");
if (TXTFiles.Length == 0)
{
    //No files present
}
foreach (var file in TXTFiles)
{
    if(file.Exists)
    {
         //.txt File exists 
    }
}
Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
0

You can do it like this

string[] files = System.IO.Directory.GetFiles(path, "*.txt");
if(files.Length >= 1)
{
    MessageBox.Show("Error Message ... Your folder still have some Txt files left");
    // or
    Console.WriteLine("Error Message ... Your folder still have some Txt files left");
}
Mohit S
  • 13,723
  • 6
  • 34
  • 69