当前位置:首页 > C#

c#采用递归非递归两种方式遍历目录下所有文件

happyfhb14年前 (2012-12-30)C#1855
摘要: 经典中的经典。 一 递归遍历参考:http://www.fenghaibin.com/post/1025.html也可以使用这种方法public void GetFiles1(string pathname) { string[…

 经典中的经典。

 

一 递归遍历

参考:http://www.fenghaibin.com/post/1025.html

也可以使用这种方法

public void GetFiles1(string pathname)     
{         
    string[] subFiles = Directory.GetFiles(pathname);         
    foreach (string subFile in subFiles)         
    {             
        Console.WriteLine(subFile);         
    }          
               
    string[] subDirs = Directory.GetDirectories(pathname);         
    foreach (string subDir in subDirs)         
    {            
        GetFiles1(subDir);         
    }     
}

 

二 非递归 在这里重点感谢 http://www.okbase.net/doc/details/2583 的作者 我在此作者基础上增加了 对无法访问目录的try 即使遇到不可访问目录也可以轻松跳过

//此函数采用非递归方式遍历问题 是所有中最好的遍历方法     
public void GetAllDirList(string pathname)     
{     
    Stack<string> skDir = new Stack<string>();       
    skDir.Push(pathname);     
    while (skDir.Count > 0)     
    {     
        pathname = skDir.Pop();     
        try
        {     
            string[] subDirs = Directory.GetDirectories(pathname);     
            string[] subFiles = Directory.GetFiles(pathname);     
            if (subDirs != null)     
            {     
                for (int i = 0; i < subDirs.Length; i++)     
                {                   
                    skDir.Push(subDirs[i]);     
                }     
           
                if (subFiles != null)     
                {     
                    for (int i = 0; i < subFiles.Length; i++)     
                    {                    
                        listBox1.Items.Add(subFiles[i]);     
                    }     
                }     
            }     
        }     
        catch (Exception ex) { }// 捕抓错误 什么都不做     
                        
    }     
}

 

扫描二维码推送至手机访问。

版权声明:本文由海海日记-冯海滨博客发布,如需转载请注明出处。

本文链接:http://www.fenghaibin.com/?id=1027

“c#采用递归非递归两种方式遍历目录下所有文件” 的相关文章

vb.net 随机函数 random 用法

VB.net 的写法dim rand as new random()i=rand.next(1,100)表示伪随机数生成器,一种能够产生满足某些随机性统计要求的数字序列的设备。命名空间:System程序集:mscorlib(在 mscorlib.dll 中)伪随机数是以相同的概率从一组有限的数字中选…

vb.net 多线程写法

注意 只能调用 不带参数的 sub 如果调用不同类的sub需要定义调用的sub是shared 是共享的 才可以的。相关语法Imports SystemImports System.Threading  '导入系统进程 Public Class Form1 &n…

IIS_WPG用户组

IIS_WPG用户组在安装asp.net web应用程序时,发现文件夹的用户权限总设置不对,结果导致读写access数据库文件出错。仔细研究了一下,发现必须要给IIS_WPG用户组足够的权限,程序才能正常运行。IIS_WPG用户组是做什么的?为了管理的方便,在安装 IIS 6 时创建了 IIS_WP…

asp.net substring截取函数详细用法

asp.net  substring截取函数详细用法字符串截取,substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。substring(int beginIndex, int endIndex)  返回一个新字符串,它是此字符串的一…

c#无返回值函数如何调用

 无返回值函数如何调用 事例 定义一个不需要返回值的函数 none()         static void none()//定义一个不需要返回值的函数        {&nbs…

学习心得 数据库连接类的书写规范

一般的规范都是建立3个类文件类1:字段(属性)model类2:方法(函数) dal类3:辅助或者就是 本来可以直接通过dal调用的方法 我在重写一遍 起中转作用 可以使程序更加清晰  bll…

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。