少有人走的路

勇哥的工业自动化技术网站

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
版权声明:本文为博主原创文章,转载请附上博文链接!


发表评论:

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

«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接

Powered By Z-BlogPHP 1.7.3

Copyright www.skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864