C#代码: 递归搜索所有子目录下的文件

一段常用的代码,取指定目录下所有的文件,并且会递归搜索所有子目录下的文件。


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            File.WriteAllText("d:\\fileList.txt", getfileNames("C:\\Users\\Administrator\\Desktop\\529\\all\\123"));
        }


        public string getfileNames(string rootPath)
        {
            StringBuilder sw = new StringBuilder();
            try
            {
                getDirectory(sw, rootPath, 2);
                return sw.ToString();
            }
            catch (IOException e)
            {
                return "";
            }

        }
        public static void getFileName(StringBuilder sw, string path, int indent,string externName)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            foreach (FileInfo f in root.GetFiles())
            {
                if (f.FullName.EndsWith(externName))
                    sw.Append(f.FullName + "\r\n");
            }
        }

        public static void getDirectory(StringBuilder sw, string path, int indent)
        {
            getFileName(sw, path, indent,".bmp");
            DirectoryInfo root = new DirectoryInfo(path);
            foreach (DirectoryInfo d in root.GetDirectories())
            {
                getDirectory(sw, d.FullName, indent + 2);
            }
        }
    }
}

--------------------- 

作者:hackpig
来源:www.skcircle.com
版权声明:本文为博主原创文章,转载请附上博文链接!


本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:

发表评论:

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

会员中心
搜索
«    2024年4月    »
1234567
891011121314
15161718192021
22232425262728
2930
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 点击查阅微信群二维码
  • 扫描加勇哥的非标自动化群,验证答案:C#/C++/VB勇哥的非标自动化群
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:
  • 留言板:

Powered By Z-BlogPHP 1.7.2

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864