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

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

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

22条回答
  •  囚心锁ツ
    2020-11-22 00:33

    Here is a version of B. Clay Shannon's code not static for excel-files:

    class ExcelSearcher
    {
        private List _fileNames;
    
        public ExcelSearcher(List filenames)
        {
            _fileNames = filenames;
        }
        public List GetExcelFiles(string dir, List filenames = null)
        {
    
            string dirName = dir;
            var dirNames = new List();
            if (filenames != null)
            {
                _fileNames.Concat(filenames);
            }
            try
            {
                foreach (string f in Directory.GetFiles(dirName))
                {
                    if (f.ToLower().EndsWith(".xls") || f.ToLower().EndsWith(".xlsx"))
                    {
                        _fileNames.Add(f);
                    }
                }
                dirNames = Directory.GetDirectories(dirName).ToList();
                foreach (string d in dirNames)
                {
                    GetExcelFiles(d, _fileNames);
                }
            }
            catch (Exception ex)
            {
                //Bam
            }
            return _fileNames;
        }
    

提交回复
热议问题