递归算法--遍历指定目录下的子目录及文件(C#.net)

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 chhwang 的 blog

//递归算法--遍历指定目录下的子目录及文件(c#.net),希望有用,顺带数据入库 

  private void button1_click(object sender, system.eventargs e)
  {
   conn.open();

   displayitems(textbox1.text);
   //messagebox.show(dirs.length.tostring());
   conn.close();
  }
 /*这里是递归算法的遍历程序部分*/
  private void displayitems(string path)
  {
   try
   {
    directoryinfo di=new directoryinfo(path);
    fileinfo[] subfiles=di.getfiles();

    filesysteminfo[] dirs = di.getdirectories();

      foreach(fileinfo filenext in subfiles)
      {
     /*-----------------------------------------------------------------------------------------------------*/
       string path_total=path + "/" +filenext.tostring();
       int path_start=path_total.indexof("/")+1;
       int path_end=path_total.lastindexof("/");
       string path_name;
       if(path_start-1==path_end)
       {
         path_name="";
       }
       else
       {
         path_name=path.substring(path_start,path_end-path_start);
       }
       switch(path_start.tostring())
       {
        case "....":
         break;
       }
     /*-----------------------------------------------------------------------------------------------------*/
       string sql="insert into pic_data(pic_name,pic_path,pic_time) values(’"+ filenext.tostring() +"’,’"+ path_name +"’,’"+ datetime.now.tostring() +"’)";
       sqlcommand cmd=new sqlcommand(sql,conn);
       if(checkbox_insertdb.checked==true)
       cmd.executenonquery();

       richtextbox1.text=richtextbox1.text + "\r\n" + path + "/" +filenext.tostring() + "  ("+sql+")";
      }
    foreach(directoryinfo dinext in dirs)
    {
     displayitems(path + "/" + dinext.tostring());
    }
   }
   catch(exception ex)
   {
    richtextbox1.text=ex.message +"\r\n"+ richtextbox1.text;
   }

  } 
 }

本文关键:递归算法--遍历指定目录下的子目录及文件(C#.net)
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top