温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用C#怎么遍历文件夹获取指定后缀名文件

发布时间:2021-02-19 16:28:21 来源:亿速云 阅读:661 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关使用C#怎么遍历文件夹获取指定后缀名文件,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
 
namespace learnGDAL
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
     
    
    private void button3_Click(object sender, EventArgs e)
    {
      List<FileInfo> lst = new List<FileInfo>();
      string strPath = @"E:\WORK\g1\北京市\北京市";
      List<FileInfo> lstFiles = getFile(strPath, ".shp",lst);
      foreach(FileInfo shpFile in lstFiles)
      {
        label3.Text += shpFile.FullName+"\n";
      }
    }
    /// <summary>
    /// 获得目录下所有文件或指定文件类型文件(包含所有子文件夹)
    /// </summary>
    /// <param name="path">文件夹路径</param>
    /// <param name="extName">扩展名可以多个 例如 .mp3.wma.rm</param>
    /// <returns>List<FileInfo></returns>
    public static List<FileInfo> getFile(string path, string extName, List<FileInfo> lst)
    {
      try
      {
        
        string[] dir = Directory.GetDirectories(path); //文件夹列表  
        DirectoryInfo fdir = new DirectoryInfo(path);
        FileInfo[] file = fdir.GetFiles();
        //FileInfo[] file = Directory.GetFiles(path); //文件列表  
        if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空          
        {
          foreach (FileInfo f in file) //显示当前目录所有文件  
          {
            if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
            {
              lst.Add(f);
            }
          }
          foreach (string d in dir)
          {
            getFile(d, extName,lst);//递归  
          }
        }
        return lst;
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }
 
    
  }
}

上述就是小编为大家分享的使用C#怎么遍历文件夹获取指定后缀名文件了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI