Quantcast
Viewing latest article 1
Browse Latest Browse All 4

Exclude specific files in file search with in a directory in C#

This article demonstrate how we can get the list of the files according specific search pattern with excluding some files. Suppose if a folder contains the following files:
 
“etest.xml”           “summerytest.xml”           “clstest.aspx”
“test1.xml”           “test1.xml”                       “reporttest.xml”
“mytest.xml”       “class.xml”                         “logtest.xml”
 
Let’s say we need to array of the all XML file names but don’t want to include the XML files starting with ‘test..’.
www.authorcode.com/search-for-an-element-in-array-with-array-find- method-in-c/
 
Solution:
For it we are using the Array.FindAll with System.Io.Direcotory.GetFiles function. And for excluding the files starting with ‘test.. we use the predicate(The Predicate is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate). See the following example:
 

  1.  private string[] GetSearchFiles(string folderpath)
  2.         {
  3.             string[] Searchfiles = Array.FindAll(System.IO.Directory.GetFiles(folderpath, "*.xml",
  4.             System.IO.SearchOption.AllDirectories), IsInclude);
  5.             return Searchfiles;
  6.         }
  7.        
  8.         bool IsInclude(string s)
  9.         {
  10.             bool i = true;
  11.             if (s.Contains("test"))
  12.             {
  13.                 i=false;
  14.             }
  15.             return i;
  16.         }

 
IsInclude procedure will call for each item in the array of the file names( from the System.IO.Directory.GetFiles) and if IsInclude function return false then Array.Find function exclude that file name.


Viewing latest article 1
Browse Latest Browse All 4

Trending Articles