我是靠谱客的博主 鲤鱼小馒头,这篇文章主要介绍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# 遍历文件夹下所有子文件夹中的文件,得到文件名

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

复制代码
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
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# 遍历文件夹及子目录下所有图片的实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对靠谱客网站的支持!

最后

以上就是鲤鱼小馒头最近收集整理的关于C# 遍历文件夹子目录下所有图片及遍历文件夹下的文件的全部内容,更多相关C#内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(128)

评论列表共有 0 条评论

立即
投稿
返回
顶部