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#遍历获取文件夹下所有文件的更多相关文章

  1. PHP遍历文件夹下的文件和获取到input name的值

    <?php$dir = dirname(__FILE__); //要遍历的目录名字 ->当前文件所在的文件夹//$dir='D:\PHP\wamp\www\admin\hosts\admi ...

  2. python (9)统计文件夹下的所有文件夹数目、统计文件夹下所有文件数目、遍历文件夹下的文件

    命令:os 用到的:os.walk   os.listdir 写的爬虫爬的数据,但是又不知道进行到哪了,于是就写了个脚本来统计文件的个数 #统计 /home/dir/ 下的文件夹个数 import o ...

  3. C#遍历文件夹下所有文件

    FolderForm.cs的代码如下: using System; using System.Collections.Generic; using System.Diagnostics; using ...

  4. java中File类应用:遍历文件夹下所有文件

    练习: 要求指定文件夹下的所有文件,包括子文件夹下的文件 代码: package 遍历文件夹所有文件; import java.io.File; public class Test { public ...

  5. Qt 获取文件夹下所有文件

    Qt 获取文件夹下所有文件代码如下: QStringList getFileNames(const QString &path) { QDir dir(path); QStringList n ...

  6. opencv实现遍历文件夹下所有文件

    前言 最近需要将视频数据集中的每个视频进行分割,分割成等长的视频片段,前提是需要首先遍历数据集文件夹中的所有视频. 实现 1.了解opencv中的Directory类: 2.实现测试代码: 系统环境 ...

  7. c bash 代码遍历文件夹下所有文件

    用C代码.bash实现代码遍历文件夹下所有文件 递归方式实现如下: void listdir(char *path) { DIR *ptr_dir; struct dirent *dir_entry; ...

  8. PHP使用glob方法遍历文件夹下所有文件

    PHP使用glob方法遍历文件夹下所有文件 遍历文件夹下所有文件,一般可以使用opendir 与 readdir 方法来遍历.<pre><?php$path = dirname(__ ...

  9. 使用boost库获取文件夹下所有文件名字

    最近整理项目发现一个曾经找了好久的有用的代码片段,就是获取文件夹下所有文件的名字,和当前文件的绝对路径. 记录一下. 使用的是boost库, #include <boost/filesystem ...

  10. FILE文件删除操作(删除指定文件夹下所有文件和文件夹包括子文件夹下所有文件和文件夹),就是删除所有

    2018-11-05  19:42:08开始写 选择 删除 1.FileUtils.java类 import java.io.File;//导入包 import java.util.List;//导入 ...

随机推荐

  1. 2.13 新手必读的Linux使用注意事项

    通过安装并体验 Linux 系统,读者应该能发现 Linux 与 Windows 的一些不同之处,本节就几个容易让初学者混淆的问题做重点讲解,以便加深读者对 Linux 系统的认识. Linux 严格 ...

  2. 2022 GDOI普及组游记

    2022 GDOI普及组游记 注:传送门均为校内网址 day -4 被年级主任集中开会,给我们免了亿堆作业,灌了亿壶鸡汤,宣布了为期一(亿)周的集训开始. day -3 中午一直在复习期中(4.21- ...

  3. 高性能计算-gemm-mpi并行计算优化(8)

    1. 目标: 矩阵A(MK) 矩阵B(KN)相乘,计算结果 C(M*N);本测试将使用不同的数据分块方式.MPI通信接口.数据循环模型,测试通信及计算效率,计算耗时为程序用户态和核心态的占用cpu时间 ...

  4. elementUI 选择开始结束日期加限制

    需求是开始结束日期不得大于当前时间,当开始日期发生变化时,结束日期不得小于开始日期且不得大于当前日期 <el-form-item label="开始日期:"> < ...

  5. The 2023 ICPC Asia Hong Kong Regional Programming Contest

    The 2023 ICPC Asia Hong Kong Regional Programming Contest A. TreeScript 给你一个根,让你构造一棵树,每个节点被创造的时候必须知道 ...

  6. ArkTs布局入门04——相对布局 & 媒体查询

    1.相对布局 1.1.概述 RelativeContainer为采用相对布局的容器,支持容器内部的子元素设置相对位置关系.子元素支持指定兄弟元素作为锚点,也支持指定父容器作为锚点,基于锚点做相对位置布 ...

  7. AI 与数据的智能融合丨大模型时代下的存储系统

    WOT 全球技术创新大会2024·北京站于 6 月 22 日圆满落幕.本届大会以"智启新纪,慧创万物"为主题,邀请到 60+ 位不同行业的专家,聚焦 AIGC.领导力.研发效能.架 ...

  8. R数据分析:跨层中介的原理和做法,实例操练

    之前有同学问过我211模型,没听过这个词,感觉怎么有这么不严肃的名字,偷偷去查了查,211模型,其实就是嵌套数据的中介的情形之一.根本上讲还是属于多水平模型的路径分析(用多水平模型跑回归也可以做中介, ...

  9. Flutter shared_preferrence报错

    Flutter shared_preferrence报错 在main函数中runApp之前添加**WidgetsFlutterBinding.ensureInitialized();确保初始化成功 v ...

  10. FineReport其他js记录

    1.js修改日期组件 背景色 边框 setTimeout(function () { var color = "#092347"; var fontColor = "wh ...