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


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

在上个项目开发中遇到这样的需求,取指定目录下面的所有图片,以表格的型式展示并显示该图片的相对路径。下面小编给大家分享C# 遍历文件夹子目录下所有图片及遍历文件夹下的文件,一起看看吧

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

服务端代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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

<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#中数组、arraylist、list、dictionary的用法与区别

C# 实现 cachehelper

C#解析xml文件的代码实例分享

C#学习记录:编写高质量代码改善整理建议1-3

C# gridcontrol的模糊查询实现代码实例

C#开发之微信小程序发送模板消息功能

asp.net实现分页(非控件,输出html代码)

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

C#实现base64处理的加密解密,编码解码的示例代码

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




打赏

取消

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

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

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

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

评论

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