Search code examples
c#countgetfiles

File count starting with


I need to generate a message that counts the number of files that starts with a specified name.

Here is the code:

Private void button1_click (...)
{
      // this is the code to count the number of files that start with a specified string
      String Path = "..."
      int fCount = Directory.GetFiles (path,"InsertImage", SearchOption.AllDirectories).Length;

      messageBox.Show("fCount");
}

It is not working for my purpose. Any suggestions?


Solution

  • Edit your existing code:

    int fCount= Directory.GetFiles(path, "InsertImage*", SearchOption.AllDirectories).Length;
    messageBox.Show(fCount);
    

    Note:

    int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directory and sub directories
    
    int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly).Length; // Will Retrieve count of all files in directory but not sub directories
    
    int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directory and sub directories