cool hit counter [C#] Recursively search for a specified item (file or directory) in a specified directory_Intefrankly

[C#] Recursively search for a specified item (file or directory) in a specified directory


--------------- update:201411201121---------------

Main update notes. Change the original bool recurse parameter to int depth, so that the recursion depth can be specified instead of the generalized whether recursion

Don't spew yet, please let me explain.

It is true that you can use the methods GetFiles, GetDirectories, GetFileSystemEntries under the ready-made Directory class to achieve the same function, but believe me it's not an egg on my face, the reason is that these methods will most likely give you an access denied exception when you encounter a directory like [System Volume Information], and you can't even skip it if you want to. On this issue, it is also stated at MSDN that

http://msdn.microsoft.com/zh-cn/library/bb513869(v=vs.90).aspx

So there's no way around it, reimplemented a bit.

Description of implementation.

- is still implemented based on wrapping several methods of the Directory class, just without using their searchPattern and searchOption functions

- Change the match pattern from the windows wildcard? , * to regular match. One is to make matching more robust, and two is to achieve ?*matching would have to do extra work that is unnecessary Matching patterns do not have first and last qualifiers added by default^$, i.e.“abc" will match all items that contain this string, So if you want to match the first and last, Please add your own^$ Ignore case matching If you do not want to search for a specific item but all, Please sendregexPattern The parameters are set tonull, rather than.*, The former performs better

- The depth parameter can be set to specify the depth of the recursive search. The default is 0, which means that only the top-level items are searched, and a positive number indicates a few levels down, while a negative number indicates an unlimited number

- The throwEx parameter can be set to indicate whether to throw an exception. The default is to not throw, when an inaccessible directory is encountered it is skipped and the traversal continues

- The reason for putting another layer of try-catch on the outer layer of foreach is that if the specified dir is the inaccessible directory, then the exception can be avoided as well. This returns string[0]

- The reason for implementing 3 methods for fetching items, fetching files, and fetching directories respectively, instead of implementing only one fetching item and overloading the other two, is that if only one is implemented, there is a lot of logical judgments to be made in foreach, and considering that the methods are recursive, the less logic in the loop the better

- The reason why the dir parameter legality check is not done is the same as above, the less judgement the better. So please make sure the dir is legal before you call

Enough crap, on to the code.

/// <summary>
 /// Get the matches (files or directories) in the specified directory
/// </summary>
/// <param name="dir"> Directory to search</param>
/// <param name="regexPattern"> item name pattern( regular (figure in geometry))。null indicates that pattern matching is ignored, Return all items</param>
/// <param name="depth"> Recursion depth。 Negative numbers indicate no limit,0 Indicates top-level only</param>
/// <param name="throwEx"> Does it throw an exception?</param>
/// <returns></returns>
public static string[] GetFileSystemEntries(string dir, string regexPattern = null, int depth = 0, bool throwEx = false)
{
    List<string> lst = new List<string>();

    try
    {
        foreach (string item in Directory.GetFileSystemEntries(dir))
        {
            try
            {
                if (regexPattern == null || Regex.IsMatch(Path.GetFileName(item), regexPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline))
                { lst.Add(item); }

                 // Recursive
                if (depth != 0 && (File.GetAttributes(item) & FileAttributes.Directory) == FileAttributes.Directory)
                { lst.AddRange(GetFileSystemEntries(item, regexPattern, depth - 1, throwEx)); }
            }
            catch { if (throwEx) { throw; } }
        }
    }
    catch { if (throwEx) { throw; } }

    return lst.ToArray();
}

/// <summary>
 /// Get the matching files in the specified directory
/// </summary>
/// <param name="dir"> Directory to search</param>
/// <param name="regexPattern"> File name pattern( regular (figure in geometry))。null indicates that pattern matching is ignored, Return all documents</param>
/// <param name="depth"> Recursion depth。 Negative numbers indicate no limit,0 Indicates top-level only</param>
/// <param name="throwEx"> Does it throw an exception?</param>
/// <returns></returns>
public static string[] GetFiles(string dir, string regexPattern = null, int depth = 0, bool throwEx = false)
{
    List<string> lst = new List<string>();

    try
    {
        foreach (string item in Directory.GetFileSystemEntries(dir))
        {
            try
            {
                bool isFile = (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 (depth != 0 && !isFile) { lst.AddRange(GetFiles(item, regexPattern, depth - 1, throwEx)); }
            }
            catch { if (throwEx) { throw; } }
        }
    }
    catch { if (throwEx) { throw; } }

    return lst.ToArray();
}

/// <summary>
 /// Get the matching directory in the specified directory
/// </summary>
/// <param name="dir"> Directory to search</param>
/// <param name="regexPattern"> table of contentsfu recording mode( regular (figure in geometry))。null indicates that pattern matching is ignored, Return to all directories</param>
/// <param name="depth"> Recursion depth。 Negative numbers indicate no limit,0 Indicates top-level only</param>
/// <param name="throwEx"> Does it throw an exception?</param>
/// <returns></returns>
public static string[] GetDirectories(string dir, string regexPattern = null, int depth = 0, bool throwEx = false)
{
    List<string> lst = new List<string>();

    try
    {
        foreach (string item in Directory.GetDirectories(dir))
        {
            try
            {
                if (regexPattern == null || Regex.IsMatch(Path.GetFileName(item), regexPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline))
                { lst.Add(item); }

                 // Recursive
                if (depth != 0) { lst.AddRange(GetDirectories(item, regexPattern, depth - 1, throwEx)); }
            }
            catch { if (throwEx) { throw; } }
        }
    }
    catch { if (throwEx) { throw; } }

    return lst.ToArray();
}

- the end of a text -


Recommended>>
1、ArcgisforJss Graphiclayer Extensions Explained
2、With this magnifying 100 times is not a dream
3、Apple selfdriving test car spotted on the streets of Silicon Valley with 64lane Lidar radar camera
4、Modelbased reinforcement learning using neural networkdriven
5、PostGISQGISGeoServerOpenLayers for data storage service publishing and map display

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号