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

来源:网络整理 责任编辑:栏目编辑 发表时间:2013-07-01 22:58 点击:

C#中遍历文件夹目录的问题
递归实现查找目录下的所有子目录和文件

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;

 

 

//------------------------------------------------------------------------------------------------------

 用asp.Net(c#)编写程序得到本机指定目录下的所有文件

首先添加引用:

using System.IO;

然后在Page_Load中编写代码:

string FilePath = "c:\test";

if(!Directory.Exists(FilePath))
   {
    Directory.CreateDirectory(FilePath);
   }
   if(!Directory.Exists(FilePath + "\Abnormal"))
   {
    Directory.CreateDirectory(FilePath + "\Abnormal");
   }

   DirectoryInfo UnPostil = new DirectoryInfo(FilePath + "\Abnormal");
   FileInfo[] ArrUnPostil = UnPostil.GetFiles();
   LB_Postil.Items.Clear();
   foreach (FileInfo FileName in ArrUnPostil)
   {
    if(FileName.Length > 0)
    {
     LB_Postil.Items.Add(FileName.Name);
    }
   }

代码中的LB_Postil是一个LISTBOX服务器控件。

    发表评论
    请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
    用户名: 验证码:点击我更换图片
    最新评论 更多>>

    推荐热点

    • 用C#制作屏幕捕获程序
    • .NET程序员项目开发必知必会—Dev环境中的集成测试用例执行时上
    • 遍历ArrayList易犯错误
    • C#对XML操作:一个处理XML文件的类(1)
    • .NET简谈反射(动态调用)
    • 使用C#编写LED样式时钟控件
    • DataList嵌套问题 如何删除内层子DataList的记录
    • 怎样用C#实现完整文档打印功能
    • .NET简谈自定义事务资源管理器
    网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
    Copyright © 2008-2015 计算机技术学习交流网. 版权所有

    豫ICP备11007008号-1