当前位置: 移动技术网 > IT编程>开发语言>c# > C# 遍历文件夹子目录下所有图片及遍历文件夹下的文件

C# 遍历文件夹子目录下所有图片及遍历文件夹下的文件

2019年07月18日  | 移动技术网IT编程  | 我要评论

要求:取指定目录下面的所有图片,以表格的型式展示并显示该图片的相对路径。

服务端代码:

 public partial class viewicon : system.web.ui.page
 {
  jarray ja = new jarray(); //定义一个数组
  public string info = string.empty; 
  protected void page_load(object sender, eventargs e)
  {
   var path1 = system.appdomain.currentdomain.basedirectory;//获取程序集目录
   string path = path.combine(path1, "image", "menu");//path.combine 将3个字符串组合成路径
   var images = directory.getfiles(path, ".", searchoption.alldirectories).where(s => s.endswith(".png") || s.endswith(".jpg") || s.endswith(".gif"));
   //images = directory.getfiles(path, "*.png|*.jpg", searchoption.alldirectories);
   //directory.getfiles 返回指定目录的文件路径 searchoption.alldirectories 指定搜索当前目录及子目录
   //遍历string 型 images数组
   foreach (var i in images){
    var str = i.replace(path1, "");//获取相对路径
    var path2 = str.replace("\\", "/");将字符“\\”转换为“/”
    ja.add(path2);
   }
   info = newtonsoft.json.jsonconvert.serializeobject(ja);//序列化为string
  }
 }

前端代码:

<script type="text/javascript">
  $(function(){
   var images = <%=info%>;
  var list = [];
  list.push("<table>");
  list.push("<thead>"); 
  list.push("<tr>"); 
  list.push("<td>图标</td>"); 
  list.push("<td>路径</td>"); 
  list.push("<td>图标</td>"); 
  list.push("<td>路径</td>");
  list.push("</tr>"); 
  list.push("</thead>");
  list.push("<tbody>");
  $.each(images, function (a,b) {
   if((a+1)%2==0){
    list.push("<td>"+"<img width='50' height='50' src = '../../" + b + "'></td>");
    list.push("<td>"+b+"</td>");
    list.push("</tr>"); 
   }
   if((a+1)%2!=0){
    list.push("<tr>"); 
    list.push("<td>"+"<img width='50' height='50' src = '../../" + b + "'></td>");
    list.push("<td>"+b+"</td>");
   } 
  })
  list.push("</tbody>");
  list.push("</table>");
  list.push("<br>");
  var images = list.join("");
  $("#imgs").append(images); 
 })
</script>

效果图如下:

下面给大家介绍下c# 遍历文件夹下所有子文件夹中的文件,得到文件名

假设a文件夹在f盘下,代码如下。将文件名输出到一个listbox中

using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.io;
namespace windowsformsapplication1
{
  public partial class form1 : form
  {
    public form1()
    {
      initializecomponent();
    }
    private void button2_click(object sender, eventargs e)
    {
      directoryinfo thefolder = new directoryinfo(@"f:\a\");
      directoryinfo[] dirinfo = thefolder.getdirectories();
      //遍历文件夹
      foreach (directoryinfo nextfolder in dirinfo)
      { 
        // this.listbox1.items.add(nextfolder.name);
        fileinfo[] fileinfo = nextfolder.getfiles();    
        foreach (fileinfo nextfile in fileinfo) //遍历文件
        this.listbox2.items.add(nextfile.name); 
      }
    }
  }
}

以上所述是小编给大家介绍的c# 遍历文件夹及子目录下所有图片的实现方法,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网