c# 获取包含子目录的指定目录下所有文件

参考:连接忘记了。。。。

        #region 查找目录下包含子目录的全部文件
        /// <summary>
        /// 获得目录下所有文件或指定文件类型文件地址
        /// </summary>
        public static List<string> fileList = new List<string>();
        public static string[] GetFiles(string fullPath, string extName, bool isFullName = false)
        {
            try
            {
                fileList.Clear();

                DirectoryInfo dirs = new DirectoryInfo(fullPath); //获得程序所在路径的目录对象
                DirectoryInfo[] dir = dirs.GetDirectories();//获得目录下文件夹对象
                FileInfo[] file = dirs.GetFiles();//获得目录下文件对象
                int dircount = dir.Count();//获得文件夹对象数量
                int filecount = file.Count();//获得文件对象数量

                //循环文件夹
                for (int i = 0; i < dircount; i++)
                {
                    string pathNode = fullPath + "\\" + dir[i].Name;
                    GetMultiFile(pathNode, isFullName);
                }

                //循环文件
                for (int j = 0; j < filecount; j++)
                {
                    if (isFullName)
                    {
                        fileList.Add(file[j].FullName);
                    }
                    else
                    {
                        fileList.Add(file[j].Name);
                    }
                }

                return fileList.ToArray();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n出错的位置为:Form1.PaintTreeView()");
            }

            return null;
        }

        private static bool GetMultiFile(string path, bool isFullName = false)
        {
            if (Directory.Exists(path) == false)
            { return false; }

            DirectoryInfo dirs = new DirectoryInfo(path); //获得程序所在路径的目录对象
            DirectoryInfo[] dir = dirs.GetDirectories();//获得目录下文件夹对象
            FileInfo[] file = dirs.GetFiles();//获得目录下文件对象
            int dircount = dir.Count();//获得文件夹对象数量
            int filecount = file.Count();//获得文件对象数量
            int sumcount = dircount + filecount;

            if (sumcount == 0)
            { return false; }

            //循环文件夹
            for (int j = 0; j < dircount; j++)
            {
                string pathNodeB = path + "\\" + dir[j].Name;
                GetMultiFile(pathNodeB, isFullName);
            }

            //循环文件
            for (int j = 0; j < filecount; j++)
            {
                if (isFullName)
                {
                    fileList.Add(file[j].FullName);
                }
                else
                {
                    fileList.Add(file[j].Name);
                }
            }
            return true;
        }

        #endregion

 

posted @ 2019-10-27 18:19  Yan327  阅读(3643)  评论(0编辑  收藏  举报