"C #" recursively searches for a specified item (file or directory) under a specified directory

Source: Internet
Author: User

Don't rush the spray first, please listen to my explanation.


It is true that the same functionality can be achieved using the GetFiles, GetDirectories, and GetFileSystemEntries methods under the existing directory classes, but believe that I am not an egg because these methods are met with "System Volume Information "This directory, it is very likely to give you a denial of access to the exception, want to skip all. So there is no way to re-implement a bit.

Implementation notes:

-is still implemented based on encapsulation of several methods of the Directory class, but not using their searchpattern and searchoption features

-Change the match pattern from Windows wildcard to regular match. One is to make the match more powerful, two is to achieve? * Matching has to do extra work, no need
The match mode does not add the ^$ by default, i.e. "ABC" will match all items that contain the string, so if you want to match the end and end, add your own ^$
Ignore case matching
If you do not want to search for the specified items but all, set the Regexpattern parameter to NULL instead of. *, the former performs better

-You can set the recurse and Throwex parameters to decide whether to search recursively, and whether to throw exceptions. Default is no recursion, no throw exception

-a directory that is inaccessible will be skipped. Of course, the premise is Throwex=false

-The reason for a layer of try-catch in the foreach shell is that if the specified dir is an inaccessible directory, it can also avoid exceptions

-The reason to get the item, get the file, get the directory to implement 3 methods, instead of implementing only one get item, the other two overloads, because only implement one, the logic of the foreach to do a lot of judgment, considering the method is recursive, so the less logic in the loop the better

-The reason why you do not check the validity of the Dir parameter is as above, the less judgment the better. So please make sure Dir is legal before you call

No nonsense, on the code:

/// <summary>///gets a match (file or directory) in the specified directory/// </summary>/// <param name= "dir" >directory to search for</param>/// <param name= "Regexpattern" >the item name pattern (regular). Null means ignore pattern match, return all items</param>/// <param name= "Recurse" >whether to search subdirectories</param>/// <param name= "Throwex" >whether to throw an exception</param>/// <returns></returns>Private Static string[] GetFileSystemEntries (stringDirstringRegexpattern =NULL,BOOLRecurse =false,BOOLThrowex =false) {List<string> LST =Newlist<string>(); Try    {        foreach(stringIteminchdirectory.getfilesystementries (dir)) {            Try            {                if(Regexpattern = =NULL|| Regex.IsMatch (Path.getfilename (item), Regexpattern, Regexoptions.ignorecase |regexoptions.multiline)) {lst. ADD (item); }                //Recursive                if(Recurse && (File.getattributes (item) & fileattributes.directory) = =fileattributes.directory) {lst. AddRange (GetFileSystemEntries (item, Regexpattern,true)); }            }            Catch{if(Throwex) {Throw; } }        }    }    Catch{if(Throwex) {Throw; } }    returnlst. ToArray ();}/// <summary>///gets the matching file in the specified directory/// </summary>/// <param name= "dir" >directory to search for</param>/// <param name= "Regexpattern" >the file name pattern (regular). Null means ignore pattern match, return all files</param>/// <param name= "Recurse" >whether to search subdirectories</param>/// <param name= "Throwex" >whether to throw an exception</param>/// <returns></returns>Private Static string[] GetFiles (stringDirstringRegexpattern =NULL,BOOLRecurse =false,BOOLThrowex =false) {List<string> LST =Newlist<string>(); Try    {        foreach(stringIteminchdirectory.getfilesystementries (dir)) {            Try            {                BOOLIsfile = (file.getattributes (item) & fileattributes.directory)! =fileattributes.directory; if(Isfile && (Regexpattern = =NULL|| Regex.IsMatch (Path.getfilename (item), Regexpattern, Regexoptions.ignorecase |regexoptions.multiline)) {lst. ADD (item); }                //Recursive                if(Recurse &&!isfile) {lst. AddRange (GetFiles (item, Regexpattern,true)); }            }            Catch{if(Throwex) {Throw; } }        }    }    Catch{if(Throwex) {Throw; } }    returnlst. ToArray ();}/// <summary>///gets the matching directory in the specified directory/// </summary>/// <param name= "dir" >directory to search for</param>/// <param name= "Regexpattern" >Directory name pattern (regular). Null means ignore pattern match, return all directories</param>/// <param name= "Recurse" >whether to search subdirectories</param>/// <param name= "Throwex" >whether to throw an exception</param>/// <returns></returns>Private Static string[] GetDirectories (stringDirstringRegexpattern =NULL,BOOLRecurse =false,BOOLThrowex =false) {List<string> LST =Newlist<string>(); Try    {        foreach(stringIteminchdirectory.getdirectories (dir)) {            Try            {                if(Regexpattern = =NULL|| Regex.IsMatch (Path.getfilename (item), Regexpattern, Regexoptions.ignorecase |regexoptions.multiline)) {lst. ADD (item); }                //Recursive                if(recurse) {lst. AddRange (GetDirectories (item, Regexpattern,true)); }            }            Catch{if(Throwex) {Throw; } }        }    }    Catch{if(Throwex) {Throw; } }    returnlst. ToArray ();}

-Wenbi-

"C #" recursively searches for a specified item (file or directory) under a specified directory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.