html5中文学习网

您的位置: 首页 > 网络编程 > ASP.NET » 正文

C#实现目标路径下文件递归的类_.NET教程_编程技术

[ ] 已经帮助:人解决问题
递归

using System;
using System.IO;
using System.Collections;

namespace DSclub
{
    /**//// <summary>
    /// DirList 的摘要说明。
    /// </summary>
    public class DirList
    {
        private string strInitFilePath;
        private bool bFatchAll;

        // 构造函数
        public DirList()
        {
            bFatchAll = false;
            strInitFilePath = "C://";
        }
        public DirList(string strFilePath)
        {
            bFatchAll = false;
            strInitFilePath = strFilePath;
        }

        // 是否递归出所有的文件
        public bool RecursionFiles
        {
            get
            {
                return bFatchAll;
            }
            set
            {
                bFatchAll = value;
            }
        }

        // 取得文件的函数
        public ArrayList GetFiles()
        {
            return GetFiles(strInitFilePath, bFatchAll);
        }

        public static ArrayList GetFiles(string strPath, bool ResultsAll)
        {
            ArrayList al  = new ArrayList();
            // 判断路径是否存在
            if(!Directory.Exists(strPath))
            {
                throw(new ApplicationException("访问的路径" + strPath + "不存在,或者它不是个文件夹。"));
            }

            string[] temp =  Directory.GetFiles(strPath);
            foreach(string aFile in temp)
            {
                al.Add(aFile);
            }

            // 如果此目录下不存在文件,则把文件夹路径返回,并用///作标识
            if(temp.Length == 0)
            {
                al.Add("///" + strPath);
            }

            if(ResultsAll)
            {
                temp = Directory.GetDirectories(strPath);
                foreach(string aDir in temp)
                {
                    al.AddRange(GetFiles(aDir, ResultsAll));
                }
            }
           
            return al;
        }

    }
}

其中关于应该有系统文件的检查,还有用户不可访问系统文件夹的判断,但是这个项目中用不上,又不想用Try块儿影响效率。

还是递归的思想!

zhVHTML5中文学习网 - HTML5先行者学习网
zhVHTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助