Share sample code to implement C# traversal of all images in folders and subdirectories

黄舟
Release: 2017-03-25 13:19:16
Original
2279 people have browsed it

这篇文章主要为大家详细介绍了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.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
  }
 }
Copy after login

前端代码:

<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=&#39;50&#39; height=&#39;50&#39; src = &#39;../../" + b + "&#39;></td>");
    list.push("<td>"+b+"</td>");
    list.push("</tr>"); 
   }
   if((a+1)%2!=0){
    list.push("<tr>"); 
    list.push("<td>"+"<img width=&#39;50&#39; height=&#39;50&#39; src = &#39;../../" + b + "&#39;></td>");
    list.push("<td>"+b+"</td>");
   } 
  })
  list.push("</tbody>");
  list.push("</table>");
  list.push("<br>");
  var images = list.join("");
  $("#imgs").append(images); 
 })

</script>
Copy after login

效果图如下:

The above is the detailed content of Share sample code to implement C# traversal of all images in folders and subdirectories. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!