How to recursively list all the files in a directory in C#?

前端 未结 22 2507
长发绾君心
长发绾君心 2020-11-22 00:07

How to recursively list all the files in a directory and child directories in C#?

22条回答
  •  天涯浪人
    2020-11-22 01:00

    Here's my angle on it, based on Hernaldo's, if you need to find files with names of a certain pattern, such as XML files that somewhere in their name contain a particular string:

    // call this like so: GetXMLFiles("Platypus", "C:\\");
    public static List GetXMLFiles(string fileType, string dir)
    {
        string dirName = dir; 
        var fileNames = new List();
        try
        {
            foreach (string f in Directory.GetFiles(dirName))
            {
                if ((f.Contains(fileType)) && (f.Contains(".XML")))
                {
                    fileNames.Add(f);
                }
            }
            foreach (string d in Directory.GetDirectories(dirName))
            {
                GetXMLFiles(fileType, d);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return fileNames;
    }
    

提交回复
热议问题