实现C#遍历文件夹及子目录下所有图片的示例代码分享


本文摘自PHP中文网,作者黄舟,侵删。

这篇文章主要为大家详细介绍了C# 遍历文件夹及子目录下所有图片的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

服务端代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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

 }

}

前端代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

<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#遍历文件夹及子目录下所有图片的示例代码分享的详细内容!

相关阅读 >>

C#向word文档插入和隐藏段落的方法介绍

C# winform制作不规则窗体(代码)

C#全应用导图的图文介绍

C# .net 将list序列化

详解C#生成随机数功能的代码示例

关于C#中三个关键字params,ref,out的详细介绍

教你用C#检测含有中文字符串的实际长度

c#中var和dynamic之间的区别是什么?

详解C#集合类型大盘点的图文代码

具体介绍C#使用selenium+phantomjs抓取数据的案例(图文)

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...