欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net遍历目录文件夹和子目录所有文件

程序员文章站 2022-12-02 11:47:23
复制代码 代码如下:using system; using system.collections.generic; using system....
复制代码 代码如下:

using system;
using system.collections.generic;
using system.text;
using system.io;
using system.threading;

namespace copefile
{
    class program
    {
        static void main(string[] args)
        {
            string testdir = "e:/xunlei/";
            listfiles(testdir,0);
            console.readkey();
        }

        public static void listfiles(string dir, int level)
        {
           //阿会楠练习作品,程序多有参考
            try
            {
                //获取文件列表
                string[] files = directory.getfiles(dir);

                string prestr = "";
                for (int i = 0; i < level; i++)
                {
                    prestr += "    ";
                }

                foreach (string f in files)
                {
                    if (f.lastindexof("\\") == -1)
                    {
                        console.writeline(prestr + f.substring(f.lastindexof("/") + 1));
                    }
                    else
                    {
                        console.writeline(prestr + f.substring(f.lastindexof("\\") + 1));
                    }

                }

                //获取目录列表
                string[] dirs = directory.getdirectories(dir);
                foreach (string d in dirs)
                {
                    if (d.lastindexof("\\") == -1)
                    {
                        console.writeline(prestr + d.substring(d.lastindexof("/") + 1));
                    }
                    else
                    {
                        console.writeline(prestr + d.substring(d.lastindexof("\\") + 1));
                    }
                    if (directory.exists(d))
                    {
                        listfiles(d, level + 1);
                    }
                }

            }
            catch (exception ex)
            {
                console.writeline(ex.message);
            }
        }
    }
}