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. 13-1 c++拷贝控制:拷贝赋值与销毁

    定义一个类时,我们必须对它进行拷贝控制,即控制该类在进行拷贝.赋值.移动和销毁时要进行哪些操作 一个类通过五个特殊的成员函数进行拷贝控制 拷贝构造函数 拷贝赋值函数 移动构造函数 移动赋值函数 析构函 ...

  2. 大便系统无法使用source的原因及解决方法

    debian中shell脚本无法使用source的原因及解决方法 现象: shell脚本中source aaa.sh时提示 source: not found 原因: ls -l `which sh` ...

  3. 联邦学习开山之作Communication-Efficient Learning of Deep Networks from Decentralized Data

    1 介绍 1.1 背景 越来越多的手机和平板电脑成为许多人的主要计算设备.这些设备上强大的传感器(包括摄像头.麦克风和GPS),加上它们经常被携带的事实,意味着它们可以访问前所未有的大量数据,其中大部 ...

  4. 20241120 校内模拟赛 T3 题解

    题目描述 给定一个数列 \(A\),数列的元素取值范围为 \([1,m]\). 请计算有多少个非空子区间满足以下条件:该区间内每个元素的出现次数都相同(没有出现的元素视为出现 \(0\) 次). 例如 ...

  5. LNMP一键安装

    PHP环境快捷搭建工具: https://lnmp.org/ [安装] wget https://soft.lnmp.com/lnmp/lnmp2.1.tar.gz -O lnmp2.1.tar.gz ...

  6. Educational Codeforces Round 102 (Rated for Div

    Educational Codeforces Round 102 (Rated for Div. 2) No More Inversions 给定\(k\),序列\(a\)长度为\(n\):\(1,2 ...

  7. qiankun 的 CSS 沙箱隔离机制

    为什么需要CSS沙箱 在 qiankun 微前端框架中,由于每个子应用的开发和部署都是独立的,将主/子应用的资源整合到一起时,容易出现样式冲突的问题 因此,需要 CSS 沙箱来解决样式冲突问题,实现主 ...

  8. Echarts 基本使用

    1.Echarts简介 ECharts 是一个使用 JavaScript 实现的开源可视化库,涵盖各行业图表,满足各种需求. ECharts 包含了以下特性: (1)丰富的可视化类型: 常规的折线图. ...

  9. 史上最牛X的微信公众号!

    今天给大家推荐一个最牛逼的微信公众号,专注分享技术干货,包括但不限于Java,HTML,JavaScript,MySQL,Redis,Windows,Linux,Spring,SpringBoot,V ...

  10. RabbitMQ, Windows Server 上服务总线的替代品

    RabbitMQ, Windows Server 上服务总线的替代品 https://www.robfox.io/2017/04/17/rabbitmq-alternative-service-bus ...