C#遍历获取文件夹下所有文件
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Linq;
5 using System.Security.Cryptography;
6 using System.Text;
7 using System.Text.RegularExpressions;
8 using System.Threading.Tasks;
9
10 namespace DataManageBLL
11 {
12 public class FileHelper
13 {
14 ///// <summary>
15 ///// 遍历获取文件夹下所有文件
16 ///// </summary>
17 ///// <param name="fileFolder">要搜索的文件夹</param>
18 ///// <param name="allfiles">返回的文件列表</param>
19 //public static void GetAllFiles(string fileFolder, ref List<string> allfiles)
20 //{
21 // DirectoryInfo Dir = new DirectoryInfo(fileFolder);
22 // FileInfo[] files = Dir.GetFiles();
23 // foreach (var fileitem in files)
24 // {
25 // allfiles.Add(fileitem.FullName);
26 // }
27 // DirectoryInfo[] directorys = Dir.GetDirectories();
28 // foreach (var directoryitem in directorys)
29 // {
30 // GetAllFiles(directoryitem.FullName, ref allfiles);
31 // }
32 //}
33
34 /// <summary>
35 /// 遍历获取文件夹下所有文件
36 /// </summary>
37 /// <param name="fileFolder">要搜索的文件夹</param>
38 /// <param name="allfiles">返回的文件列表</param>
39 public static void GetAllFiles(string fileFolder, ref List<string> allfiles, string ext = null, DateTime? startTime = null)
40 {
41 DateTime lastUploadDateTime = DateTime.MinValue;
42 GetAllFiles(fileFolder, ref allfiles, ref lastUploadDateTime, ext, startTime);
43 }
44
45 public static void GetAllFilesByImgPath(string decPath, ref List<string> allfiles, ref List<DateTime> lastUploadTimeList, string ext = null, DateTime? startTime = null)
46 {
47 DirectoryInfo Dir = new DirectoryInfo(decPath);
48
49 DirectoryInfo[] files = Dir.GetDirectories();
50 if (files != null && files.Count() > 0)
51 {
52 if (!string.IsNullOrEmpty(ext))
53 {
54 Regex regex = new Regex(ext);
55 files = files.Where(x => x.LastWriteTime > startTime).Where(x => regex.IsMatch(x.Name)).OrderBy(x => x.LastWriteTime).ToArray();
56 }
57 else
58 files = files.Where(x => x.LastWriteTime > startTime).OrderBy(x => x.LastWriteTime).ToArray();
59
60 if (startTime.HasValue)
61 {
62 foreach (var item in files)
63 {
64 allfiles.Add(item.FullName);
65 lastUploadTimeList.Add(item.LastWriteTime);
66 }
67 }
68 }
69 }
70
71 /// <summary>
72 /// 遍历获取文件夹下所有文件
73 /// </summary>
74 /// <param name="fileFolder">要搜索的文件夹</param>
75 /// <param name="allfiles">返回的文件列表</param>
76 public static void GetAllFiles(string fileFolder, ref List<string> allfiles, ref DateTime lastUploadTime, string ext = null, DateTime? startTime = null)
77 {
78 DirectoryInfo Dir = new DirectoryInfo(fileFolder);
79
80 FileInfo[] files = new FileInfo[] { };
81 if (Dir.Exists)
82 files = Dir.GetFiles();
83 foreach (var fileitem in files)
84 {
85 if (startTime == null || (startTime != null && fileitem.LastWriteTime < startTime.Value))
86 {
87 if (string.IsNullOrEmpty(ext))
88 {
89 allfiles.Add(fileitem.FullName);
90 if (lastUploadTime < fileitem.LastWriteTime)
91 {
92 lastUploadTime = fileitem.LastWriteTime;
93 }
94 }
95 else
96 {
97 string fileExt = Path.GetExtension(fileitem.FullName);
98 if (fileExt.ToLower() == ext.ToLower())
99 {
100 allfiles.Add(fileitem.FullName);
101 if (lastUploadTime < fileitem.LastWriteTime)
102 {
103 lastUploadTime = fileitem.LastWriteTime;
104 }
105 }
106 }
107 }
108 }
109 DirectoryInfo[] directorys = Dir.GetDirectories();
110 foreach (var directoryitem in directorys)
111 {
112 //if (startTime == null || (startTime != null && directoryitem.LastWriteTime < startTime.Value))
113 GetAllFiles(directoryitem.FullName, ref allfiles, ref lastUploadTime, ext, startTime);
114 }
115 }
116
117 /// <summary>
118 /// 遍历获取文件夹下所有文件
119 /// </summary>
120 /// <param name="fileFolder">要搜索的文件夹</param>
121 /// <param name="allfiles">返回的文件列表</param>
122 public static void DeleteFiles(string fileFolder, ref List<string> allfiles, string ext = null, DateTime? startTime = null)
123 {
124 DateTime lastUploadDateTime = DateTime.MinValue;
125 DeleteFilesDetail(fileFolder, ref allfiles, ref lastUploadDateTime, ext, startTime);
126 }
127
128
129 /// <summary>
130 /// 遍历获取文件夹下所有文件
131 /// </summary>
132 /// <param name="fileFolder">要搜索的文件夹</param>
133 /// <param name="allfiles">返回的文件列表</param>
134 public static void DeleteFilesDetail(string fileFolder, ref List<string> allfiles, ref DateTime lastUploadTime, string ext = null, DateTime? startTime = null)
135 {
136 DirectoryInfo Dir = new DirectoryInfo(fileFolder);
137
138 FileInfo[] files = new FileInfo[] { };
139 if (Dir.Exists)
140 files = Dir.GetFiles();
141 foreach (var fileitem in files)
142 {
143 if (startTime == null || (startTime != null && fileitem.LastWriteTime < startTime.Value))
144 {
145 try
146 {
147 File.Delete(fileitem.FullName);
148 }
149 catch (Exception ex)
150 {
151 continue;
152 }
153 }
154 }
155 DirectoryInfo[] directorys = Dir.GetDirectories();
156 foreach (var directoryitem in directorys)
157 {
158 //if (startTime == null || (startTime != null && directoryitem.LastWriteTime < startTime.Value))
159 DeleteFilesDetail(directoryitem.FullName, ref allfiles, ref lastUploadTime, ext, startTime);
160 }
161 }
162
163
164 public static void GetAllFilesByPath(string decPath, ref List<string> allfiles, ref List<DateTime> lastUploadTimeList, string ext = null, DateTime? startTime = null)
165 {
166 DirectoryInfo Dir = new DirectoryInfo(decPath);
167
168 FileInfo[] files = Dir.GetFiles();
169
170 if (files != null && files.Count() > 0)
171 {
172 files = files.Where(x => x.LastWriteTime > startTime).ToArray();
173 if (startTime.HasValue)
174 {
175 foreach (var item in files)
176 {
177 if (!string.IsNullOrEmpty(ext))
178 {
179 if (item.Extension.ToLower() == ext.ToLower())
180 {
181 allfiles.Add(item.FullName);
182 lastUploadTimeList.Add(item.LastWriteTime);
183 }
184 }
185 else if (string.IsNullOrEmpty(item.Extension))
186 {
187 allfiles.Add(item.FullName);
188 lastUploadTimeList.Add(item.LastWriteTime);
189 }
190 }
191 }
192 }
193
194 DirectoryInfo[] fileDireS = Dir.GetDirectories();
195 if (fileDireS != null && fileDireS.Count() > 0)
196 {
197 foreach (var item in fileDireS)
198 {
199 GetAllFilesByPath(item.FullName, ref allfiles, ref lastUploadTimeList, ext, startTime);
200 }
201 }
202 }
203
204 /// <summary>
205 /// 根据文件路径获取文件字节流
206 /// </summary>
207 /// <param name="filePath"></param>
208 /// <returns></returns>
209 public static byte[] GetFileToBytes(string filePath)
210 {
211 System.IO.Stream sm = GetFile(filePath);
212 byte[] buffer;
213 if (sm != null)
214 {
215 buffer = new byte[sm.Length];
216 sm.Read(buffer, 0, (int)sm.Length);
217 sm.Close();
218
219 return buffer;
220 }
221 return null;
222 }
223
224 /// <summary>
225 /// 根据文件路径获取文件流
226 /// </summary>
227 /// <param name="filePath"></param>
228 /// <returns></returns>
229 public static Stream GetFile(string filePath)
230 {
231 if (File.Exists(filePath))
232 {
233 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
234 return fs;
235 }
236 return null;
237 }
238
239 /// <summary>
240 /// 获取目录下的所有子目录
241 /// </summary>
242 /// <param name="fileFolder"></param>
243 /// <returns></returns>
244 public static List<string> GetAllDirectorys(string fileFolder, DateTime? startTime = null)
245 {
246 if (!Directory.Exists(fileFolder))
247 {
248 //路径不存在
249 return null;
250 }
251 DirectoryInfo Dir = new DirectoryInfo(fileFolder);
252 if (startTime == null)
253 return Dir.GetDirectories().Select(i => i.FullName).ToList();
254 else
255 return Dir.GetDirectories().Where(i => i.CreationTime <= startTime).Select(i => i.FullName).ToList();
256 }
257
258 /// <summary>
259 /// 获取文件的MD5哈希值
260 /// </summary>
261 /// <param name="filePath">文件名</param>
262 /// <returns></returns>
263 public static string GetFileMD5Hash(string filePath)
264 {
265 FileStream get_file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
266 MD5CryptoServiceProvider get_md5 = new MD5CryptoServiceProvider();
267 byte[] hash_byte = get_md5.ComputeHash(get_file);
268 get_file.Close();
269 string result = BitConverter.ToString(hash_byte);
270 return result.Replace("-", "");
271 }
272
273 /// <summary>
274 /// 获取某个流的MD5值
275 /// 注:流必须先seek(0,begin)
276 /// </summary>
277 /// <param name="stream"></param>
278 /// <returns></returns>
279 public static string GetStreamMD5Hash(Stream stream)
280 {
281 MD5CryptoServiceProvider get_md5 = new MD5CryptoServiceProvider();
282 byte[] hash_byte = get_md5.ComputeHash(stream);
283 string result = BitConverter.ToString(hash_byte);
284 return result.Replace("-", "");
285 }
286
287 /// <summary>
288 /// 删除文件
289 /// </summary>
290 /// <param name="filePath"></param>
291 public static void FileDelete(string filePath)
292 {
293 if (File.Exists(filePath))
294 {
295 File.Delete(filePath);
296 }
297 }
298
299 /// <summary>
300 /// 移动文件(多个)
301 /// </summary>
302 /// <param name="srcFileFullPathes">源文件(数组)</param>
303 /// <param name="destFileSubPathes">目标文件(数组)</param>
304 /// <param name="isOverwrite">是否覆盖</param>
305 /// <returns>
306 /// 拷贝后文件的全路径
307 /// </returns>
308 public static void Move(string[] srcFileFullPathes, string[] destFileFullPathes, bool isOverwrite)
309 {
310 //参数检查
311 if (srcFileFullPathes.Length != destFileFullPathes.Length)
312 {
313 throw new Exception("[源文件个数]与[目标文件个数]不匹配!");
314 }
315 //检查目标路径是否存在,不存在就创建
316 for (int i = 0; i < destFileFullPathes.Length; i++)
317 {
318 //路径相同不检查目录
319 if (string.Compare(srcFileFullPathes[i], destFileFullPathes[i]) == 0)
320 {
321 continue;
322 }
323 //检查目标文件目录
324 CheckDirectory(destFileFullPathes[i]);
325 }
326 try
327 {
328 for (int i = 0; i < srcFileFullPathes.Length; i++)
329 {
330 //路径相同不移动
331 if (string.Compare(srcFileFullPathes[i], destFileFullPathes[i]) == 0) continue;
332
333 if (!File.Exists(destFileFullPathes[i]))
334 {
335 //移动文件
336 File.Move(srcFileFullPathes[i], destFileFullPathes[i]);
337 }
338 else if (isOverwrite)
339 { //覆盖
340 File.Delete(destFileFullPathes[i]);
341
342 File.Move(srcFileFullPathes[i], destFileFullPathes[i]);
343 }
344 }
345 }
346 catch (Exception ex)
347 {
348 throw;
349 }
350 }
351
352 /// <summary>
353 /// 检查目录是否存在,不存在就创建目录
354 /// </summary>
355 /// <param name="filePath"></param>
356 public static void CheckDirectory(string filePath)
357 {
358 string directory = filePath.Substring(0, filePath.LastIndexOf(@"\"));
359 if (!Directory.Exists(directory))
360 {
361 try
362 {
363 Directory.CreateDirectory(directory);
364 }
365 catch (Exception ex)
366 {
367 throw;
368 }
369 }
370
371 }
372
373 /// <summary>
374 /// 将A文件夹里面的文件和文件夹移动到B文件夹
375 /// </summary>
376 /// <param name="sourcedirectory"></param>
377 /// <param name="destinationdirectory"></param>
378 public static void FolderMoveToNewFolder(string sourcedirectory, string destinationdirectory)
379 {
380 try
381 {
382 DirectoryInfo nowFolder = new DirectoryInfo(sourcedirectory);
383 destinationdirectory = Path.Combine(destinationdirectory, nowFolder.Name);
384
385 if (!Directory.Exists(destinationdirectory))
386 Directory.CreateDirectory(destinationdirectory);
387
388 string[] fileList = Directory.GetFileSystemEntries(sourcedirectory);
389 foreach (string file in fileList)
390 {
391 if (Directory.Exists(destinationdirectory))
392 {
393 //Directory.Move(file, destinationdirectory);
394 DirectoryInfo folder = new DirectoryInfo(file);
395 string strCreateFileName = destinationdirectory + "\\" + folder.Name;
396 if (!Directory.Exists(strCreateFileName))
397 folder.MoveTo(strCreateFileName);
398 else
399 folder.Delete();
400 }
401 else
402 Directory.Move(sourcedirectory, destinationdirectory);
403
404
405
406 if (File.Exists(file))
407 {
408 File.Move(file, destinationdirectory);
409 //FileInfo fi = new FileInfo(file);
410 //fi.MoveTo(newFolderPath);
411 }
412 }
413 }
414 catch (Exception ex)
415 {
416 }
417 }
418 }
419 }
我一般使用“GetAllFiles”,“DeleteFiles”方法。可以自行决定用哪一个方法
C#遍历获取文件夹下所有文件的更多相关文章
- PHP遍历文件夹下的文件和获取到input name的值
<?php$dir = dirname(__FILE__); //要遍历的目录名字 ->当前文件所在的文件夹//$dir='D:\PHP\wamp\www\admin\hosts\admi ...
- python (9)统计文件夹下的所有文件夹数目、统计文件夹下所有文件数目、遍历文件夹下的文件
命令:os 用到的:os.walk os.listdir 写的爬虫爬的数据,但是又不知道进行到哪了,于是就写了个脚本来统计文件的个数 #统计 /home/dir/ 下的文件夹个数 import o ...
- C#遍历文件夹下所有文件
FolderForm.cs的代码如下: using System; using System.Collections.Generic; using System.Diagnostics; using ...
- java中File类应用:遍历文件夹下所有文件
练习: 要求指定文件夹下的所有文件,包括子文件夹下的文件 代码: package 遍历文件夹所有文件; import java.io.File; public class Test { public ...
- Qt 获取文件夹下所有文件
Qt 获取文件夹下所有文件代码如下: QStringList getFileNames(const QString &path) { QDir dir(path); QStringList n ...
- opencv实现遍历文件夹下所有文件
前言 最近需要将视频数据集中的每个视频进行分割,分割成等长的视频片段,前提是需要首先遍历数据集文件夹中的所有视频. 实现 1.了解opencv中的Directory类: 2.实现测试代码: 系统环境 ...
- c bash 代码遍历文件夹下所有文件
用C代码.bash实现代码遍历文件夹下所有文件 递归方式实现如下: void listdir(char *path) { DIR *ptr_dir; struct dirent *dir_entry; ...
- PHP使用glob方法遍历文件夹下所有文件
PHP使用glob方法遍历文件夹下所有文件 遍历文件夹下所有文件,一般可以使用opendir 与 readdir 方法来遍历.<pre><?php$path = dirname(__ ...
- 使用boost库获取文件夹下所有文件名字
最近整理项目发现一个曾经找了好久的有用的代码片段,就是获取文件夹下所有文件的名字,和当前文件的绝对路径. 记录一下. 使用的是boost库, #include <boost/filesystem ...
- FILE文件删除操作(删除指定文件夹下所有文件和文件夹包括子文件夹下所有文件和文件夹),就是删除所有
2018-11-05 19:42:08开始写 选择 删除 1.FileUtils.java类 import java.io.File;//导入包 import java.util.List;//导入 ...
随机推荐
- 15-1 OOP概述
目录 核心思想 继承 动态绑定 核心思想 面向对象程序设计(object-oriented programming)的核心思想是 封装:类的接口和实现分离 继承:定义相似的类型并对相似关系建模 动态绑 ...
- IIC通信协议详解 & PCF8591应用(Verilog实现)
该文章结合PCF8591 8-bit AD/DA 模数/数模转换器来详细介绍IIC通信协议,尽量做到条理清晰,通俗易懂.该文图片均从PCF8591手册中截取,一定程度上引导读者学习阅读data she ...
- 基于Java+SpringBoot+Mysql实现的古诗词平台功能设计与实现四
一.前言介绍: 1.1 项目摘要 随着信息技术的迅猛发展和数字化时代的到来,传统文化与现代科技的融合已成为一种趋势.古诗词作为中华民族的文化瑰宝,具有深厚的历史底蕴和独特的艺术魅力.然而,在现代社会中 ...
- npm : 无法加载文件 D:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚本
升级node和npm之后,npm run dev 启动一个Vue项目,报错如下: npm : 无法加载文件 D:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚本. ...
- element ui table+分页 筛选全部数据
1. @filter-change 要写在table根元素,也就是<el-table @filter-change="filterChange"></el-tab ...
- Django Admin之常用功能汇总
1.字段支持下拉搜索框 1)在admin中新增字段autocomplete_fields autocomplete_fields = ("field1","field2& ...
- 大语言模型中的MoE
1.概述 MoE代表"混合专家模型"(Mixture of Experts),这是一种架构设计,通过将不同的子模型(即专家)结合起来进行任务处理.与传统的模型相比,MoE结构能够动 ...
- FineReport取消强制分页和调整宽度的设置方法
在decision里,找到管理系统-目录管理,打开相应挂载的报表,在参数设置里,添加以下内容: _bypagesize_ 字符串 false
- 《数据万象带你玩转视图场景》第一期:avif图片压缩详解
前言 随着硬件的发展,不管是手机还是专业摄像设备拍出的图片随便可能就有几M,甚至几十M,并且现在我们处于随处可及的信息海洋里,海量的图片带来了存储问题.带宽问题.加载时延问题等等.对图片信息进行有效的 ...
- .NET 单文件执行程序拆解器 SingleFileExtractor
.NET 单文件执行程序拆解器 SingleFileExtractor .NET 现在支持将程序打包为单文件格式,这方便了部署,问题是,我们不能直接看到程序中使用了哪些 DLL,更不能简单地通过查看文 ...