好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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

服务端代码:

?

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测试数据bine(path1, "image" , "menu" ); //path测试数据bine 将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>

效果图如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://HdhCmsTestcnblogs测试数据/zhibu/archive/2017/01/24/6346502.html

dy("nrwz");

查看更多关于C#遍历文件夹及子目录下所有图片的详细内容...

  阅读:49次