分享

C#中遍历文件夹目录的问题

 悟静 2011-12-16
递归实现查找目录下的所有子目录和文件

public   void   FindFile(string   dir)                           //参数为指定的目录
{    
//在指定目录及子目录下查找文件,在listBox1中列出子目录及文件
DirectoryInfo   Dir=new   DirectoryInfo(dir);
try
{
      foreach(DirectoryInfo   d   in   Dir.GetDirectories())     //查找子目录  
{
FindFile(Dir+d.ToString()+"\\");
listBox1.Items.Add(Dir+d.ToString()+"\\");       //listBox1中填加目录名
}
      foreach(FileInfo   f   in   Dir.GetFiles("*.*"))             //查找文件
{
listBox1.Items.Add(Dir+f.ToString());     //listBox1中填加文件名
}
}
catch(Exception   e)
{
MessageBox.Show(e.Message);
}

}




调用
private   void   button1_Click(object   sender,   System.EventArgs   e)
{
string   currentdir="F:\\myprogram\\C#\\FileSearch";     //搜索的目录
if(currentdir[currentdir.Length-1]!='\\')   //非根目录
currentdir+="\\";  
FindFile(currentdir);     //调用查找文件函数
}

加上   using   System.IO;

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多