.NET 文件相关的所有操作

  1 public static class FileSystemHelper
  2     {
  3         #region 检测指定目录是否存在
  4         /// <summary>
  5         /// 检测指定目录是否存在
  6         /// </summary>
  7         /// <param name="directoryPath">目录的绝对路径</param>
  8         /// <returns></returns>
  9         public static bool IsExistDirectory(string directoryPath)
 10         {
 11             return Directory.Exists(directoryPath);
 12         }
 13         #endregion
 14 
 15         #region 检测指定文件是否存在,如果存在返回true
 16         /// <summary>
 17         /// 检测指定文件是否存在,如果存在则返回true。
 18         /// </summary>
 19         /// <param name="filePath">文件的绝对路径</param>        
 20         public static bool IsExistFile(string filePath)
 21         {
 22             return File.Exists(filePath);
 23         }
 24         #endregion
 25 
 26         #region 获取指定目录中的文件列表
 27         /// <summary>
 28         /// 获取指定目录中所有文件列表
 29         /// </summary>
 30         /// <param name="directoryPath">指定目录的绝对路径</param>        
 31         public static string[] GetFileNames(string directoryPath)
 32         {
 33             //如果目录不存在,则抛出异常
 34             if (!IsExistDirectory(directoryPath))
 35             {
 36                 throw new FileNotFoundException();
 37             }
 38 
 39             //获取文件列表
 40             return Directory.GetFiles(directoryPath);
 41         }
 42         #endregion
 43 
 44         #region 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
 45         /// <summary>
 46         /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
 47         /// </summary>
 48         /// <param name="directoryPath">指定目录的绝对路径</param>        
 49         public static string[] GetDirectories(string directoryPath)
 50         {
 51             try
 52             {
 53                 return Directory.GetDirectories(directoryPath);
 54             }
 55             catch (IOException ex)
 56             {
 57                 throw ex;
 58             }
 59         }
 60         #endregion
 61 
 62         #region 获取指定目录及子目录中所有文件列表
 63         /// <summary>
 64         /// 获取指定目录及子目录中所有文件列表
 65         /// </summary>
 66         /// <param name="directoryPath">指定目录的绝对路径</param>
 67         /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
 68         /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
 69         /// <param name="isSearchChild">是否搜索子目录</param>
 70         public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild)
 71         {
 72             //如果目录不存在,则抛出异常
 73             if (!IsExistDirectory(directoryPath))
 74             {
 75                 throw new FileNotFoundException();
 76             }
 77 
 78             try
 79             {
 80                 if (isSearchChild)
 81                 {
 82                     return Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
 83                 }
 84                 else
 85                 {
 86                     return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
 87                 }
 88             }
 89             catch (IOException ex)
 90             {
 91                 throw ex;
 92             }
 93         }
 94         #endregion
 95 
 96         #region 检测指定目录是否为空
 97         /// <summary>
 98         /// 检测指定目录是否为空
 99         /// </summary>
100         /// <param name="directoryPath">指定目录的绝对路径</param>        
101         public static bool IsEmptyDirectory(string directoryPath)
102         {
103             try
104             {
105                 //判断是否存在文件
106                 string[] fileNames = GetFileNames(directoryPath);
107                 if (fileNames.Length > 0)
108                 {
109                     return false;
110                 }
111 
112                 //判断是否存在文件夹
113                 string[] directoryNames = GetDirectories(directoryPath);
114                 if (directoryNames.Length > 0)
115                 {
116                     return false;
117                 }
118 
119                 return true;
120             }
121             catch
122             {
123                 //这里记录日志
124                 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
125                 return true;
126             }
127         }
128         #endregion
129 
130         #region 检测指定目录中是否存在指定的文件
131         /// <summary>
132         /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法.
133         /// </summary>
134         /// <param name="directoryPath">指定目录的绝对路径</param>
135         /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
136         /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>        
137         public static bool Contains(string directoryPath, string searchPattern)
138         {
139             try
140             {
141                 //获取指定的文件列表
142                 string[] fileNames = GetFileNames(directoryPath, searchPattern, false);
143 
144                 //判断指定文件是否存在
145                 if (fileNames.Length == 0)
146                 {
147                     return false;
148                 }
149                 else
150                 {
151                     return true;
152                 }
153             }
154             catch (Exception ex)
155             {
156                 throw new Exception(ex.Message);
157                 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
158             }
159         }
160 
161         /// <summary>
162         /// 检测指定目录中是否存在指定的文件
163         /// </summary>
164         /// <param name="directoryPath">指定目录的绝对路径</param>
165         /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
166         /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 
167         /// <param name="isSearchChild">是否搜索子目录</param>
168         public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild)
169         {
170             try
171             {
172                 //获取指定的文件列表
173                 string[] fileNames = GetFileNames(directoryPath, searchPattern, true);
174 
175                 //判断指定文件是否存在
176                 if (fileNames.Length == 0)
177                 {
178                     return false;
179                 }
180                 else
181                 {
182                     return true;
183                 }
184             }
185             catch (Exception ex)
186             {
187                 throw new Exception(ex.Message);
188                 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
189             }
190         }
191         #endregion
192 
193         #region 创建目录
194         /// <summary>
195         /// 创建目录
196         /// </summary>
197         /// <param name="dir">要创建的目录路径包括目录名</param>
198         public static void CreateDir(string dir)
199         {
200             if (dir.Length == 0) return;
201             if (!Directory.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir))
202                 Directory.CreateDirectory(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir);
203         }
204         #endregion
205 
206         #region 删除目录
207         /// <summary>
208         /// 删除目录
209         /// </summary>
210         /// <param name="dir">要删除的目录路径和名称</param>
211         public static void DeleteDir(string dir)
212         {
213             if (dir.Length == 0) return;
214             if (Directory.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir))
215                 Directory.Delete(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir);
216         }
217         #endregion
218 
219         #region 删除文件
220         /// <summary>
221         /// 删除文件
222         /// </summary>
223         /// <param name="file">要删除的文件路径和名称</param>
224         public static void DeleteFile(string file)
225         {
226             if (File.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + file))
227                 File.Delete(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + file);
228         }
229         #endregion
230 
231         #region 创建文件
232         /// <summary>
233         /// 创建文件
234         /// </summary>
235         /// <param name="dir">带后缀的文件名</param>
236         /// <param name="pagestr">文件内容</param>
237         public static void CreateFile(string dir, string pagestr)
238         {
239             dir = dir.Replace("/", "\\");
240             if (dir.IndexOf("\\") > -1)
241                 CreateDir(dir.Substring(0, dir.LastIndexOf("\\")));
242             System.IO.StreamWriter sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir, false, System.Text.Encoding.GetEncoding("GB2312"));
243             sw.Write(pagestr);
244             sw.Close();
245         }
246         #endregion
247 
248         #region 移动文件(剪贴--粘贴)
249         /// <summary>
250         /// 移动文件(剪贴--粘贴)
251         /// </summary>
252         /// <param name="dir1">要移动的文件的路径及全名(包括后缀)</param>
253         /// <param name="dir2">文件移动到新的位置,并指定新的文件名</param>
254         public static void MoveFile(string dir1, string dir2)
255         {
256             dir1 = dir1.Replace("/", "\\");
257             dir2 = dir2.Replace("/", "\\");
258             if (File.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1))
259                 File.Move(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1, System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir2);
260         }
261         #endregion
262 
263         #region 复制文件
264         /// <summary>
265         /// 复制文件
266         /// </summary>
267         /// <param name="dir1">要复制的文件的路径已经全名(包括后缀)</param>
268         /// <param name="dir2">目标位置,并指定新的文件名</param>
269         public static void CopyFile(string dir1, string dir2)
270         {
271             dir1 = dir1.Replace("/", "\\");
272             dir2 = dir2.Replace("/", "\\");
273             if (File.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1))
274             {
275                 File.Copy(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1, System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir2, true);
276             }
277         }
278         #endregion
279 
280         #region 根据时间得到目录名 / 格式:yyyyMMdd 或者 HHmmssff
281         /// <summary>
282         /// 根据时间得到目录名yyyyMMdd
283         /// </summary>
284         /// <returns></returns>
285         public static string GetDateDir()
286         {
287             return DateTime.Now.ToString("yyyyMMdd");
288         }
289         /// <summary>
290         /// 根据时间得到文件名HHmmssff
291         /// </summary>
292         /// <returns></returns>
293         public static string GetDateFile()
294         {
295             return DateTime.Now.ToString("HHmmssff");
296         }
297         #endregion
298 
299         #region 复制文件夹
300         /// <summary>
301         /// 复制文件夹(递归)
302         /// </summary>
303         /// <param name="varFromDirectory">源文件夹路径</param>
304         /// <param name="varToDirectory">目标文件夹路径</param>
305         public static void CopyFolder(string varFromDirectory, string varToDirectory)
306         {
307             Directory.CreateDirectory(varToDirectory);
308 
309             if (!Directory.Exists(varFromDirectory)) return;
310 
311             string[] directories = Directory.GetDirectories(varFromDirectory);
312 
313             if (directories.Length > 0)
314             {
315                 foreach (string d in directories)
316                 {
317                     CopyFolder(d, varToDirectory + d.Substring(d.LastIndexOf("\\")));
318                 }
319             }
320             string[] files = Directory.GetFiles(varFromDirectory);
321             if (files.Length > 0)
322             {
323                 foreach (string s in files)
324                 {
325                     File.Copy(s, varToDirectory + s.Substring(s.LastIndexOf("\\")), true);
326                 }
327             }
328         }
329         #endregion
330 
331         #region 检查文件,如果文件不存在则创建
332         /// <summary>
333         /// 检查文件,如果文件不存在则创建  
334         /// </summary>
335         /// <param name="FilePath">路径,包括文件名</param>
336         public static void ExistsFile(string FilePath)
337         {
338             //if(!File.Exists(FilePath))    
339             //File.Create(FilePath);    
340             //以上写法会报错,详细解释请看下文.........   
341             if (!File.Exists(FilePath))
342             {
343                 FileStream fs = File.Create(FilePath);
344                 fs.Close();
345             }
346         }
347         #endregion
348 
349         #region 删除指定文件夹对应其他文件夹里的文件
350         /// <summary>
351         /// 删除指定文件夹对应其他文件夹里的文件
352         /// </summary>
353         /// <param name="varFromDirectory">指定文件夹路径</param>
354         /// <param name="varToDirectory">对应其他文件夹路径</param>
355         public static void DeleteFolderFiles(string varFromDirectory, string varToDirectory)
356         {
357             Directory.CreateDirectory(varToDirectory);
358 
359             if (!Directory.Exists(varFromDirectory)) return;
360 
361             string[] directories = Directory.GetDirectories(varFromDirectory);
362 
363             if (directories.Length > 0)
364             {
365                 foreach (string d in directories)
366                 {
367                     DeleteFolderFiles(d, varToDirectory + d.Substring(d.LastIndexOf("\\")));
368                 }
369             }
370 
371 
372             string[] files = Directory.GetFiles(varFromDirectory);
373 
374             if (files.Length > 0)
375             {
376                 foreach (string s in files)
377                 {
378                     File.Delete(varToDirectory + s.Substring(s.LastIndexOf("\\")));
379                 }
380             }
381         }
382         #endregion
383 
384         #region 从文件的绝对路径中获取文件名( 包含扩展名 )
385         /// <summary>
386         /// 从文件的绝对路径中获取文件名( 包含扩展名 )
387         /// </summary>
388         /// <param name="filePath">文件的绝对路径</param>        
389         public static string GetFileName(string filePath)
390         {
391             //获取文件的名称
392             FileInfo fi = new FileInfo(filePath);
393             return fi.Name;
394         }
395         #endregion
396 
397         #region 创建一个目录
398         /// <summary>
399         /// 创建一个目录
400         /// </summary>
401         /// <param name="directoryPath">目录的绝对路径</param>
402         public static void CreateDirectory(string directoryPath)
403         {
404             //如果目录不存在则创建该目录
405             if (!IsExistDirectory(directoryPath))
406             {
407                 Directory.CreateDirectory(directoryPath);
408             }
409         }
410         #endregion
411 
412         #region 创建一个文件
413         /// <summary>
414         /// 创建一个文件。
415         /// </summary>
416         /// <param name="filePath">文件的绝对路径</param>
417         public static void CreateFile(string filePath)
418         {
419             try
420             {
421                 //如果文件不存在则创建该文件
422                 if (!IsExistFile(filePath))
423                 {
424                     //创建一个FileInfo对象
425                     FileInfo file = new FileInfo(filePath);
426 
427                     //创建文件
428                     FileStream fs = file.Create();
429 
430                     //关闭文件流
431                     fs.Close();
432                 }
433             }
434             catch (Exception ex)
435             {
436                 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
437                 throw ex;
438             }
439         }
440 
441         /// <summary>
442         /// 创建一个文件,并将字节流写入文件。
443         /// </summary>
444         /// <param name="filePath">文件的绝对路径</param>
445         /// <param name="buffer">二进制流数据</param>
446         public static void CreateFile(string filePath, byte[] buffer)
447         {
448             try
449             {
450                 //如果文件不存在则创建该文件
451                 if (!IsExistFile(filePath))
452                 {
453                     //创建一个FileInfo对象
454                     FileInfo file = new FileInfo(filePath);
455 
456                     //创建文件
457                     FileStream fs = file.Create();
458 
459                     //写入二进制流
460                     fs.Write(buffer, 0, buffer.Length);
461 
462                     //关闭文件流
463                     fs.Close();
464                 }
465             }
466             catch (Exception ex)
467             {
468                 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
469                 throw ex;
470             }
471         }
472         #endregion
473 
474         #region 获取文本文件的行数
475         /// <summary>
476         /// 获取文本文件的行数
477         /// </summary>
478         /// <param name="filePath">文件的绝对路径</param>        
479         public static int GetLineCount(string filePath)
480         {
481             //将文本文件的各行读到一个字符串数组中
482             string[] rows = File.ReadAllLines(filePath);
483 
484             //返回行数
485             return rows.Length;
486         }
487         #endregion
488 
489         #region 获取一个文件的长度
490         /// <summary>
491         /// 获取一个文件的长度,单位为Byte
492         /// </summary>
493         /// <param name="filePath">文件的绝对路径</param>        
494         public static int GetFileSize(string filePath)
495         {
496             //创建一个文件对象
497             FileInfo fi = new FileInfo(filePath);
498 
499             //获取文件的大小
500             return (int)fi.Length;
501         }
502         #endregion
503 
504         #region 获取指定目录中的子目录列表
505         /// <summary>
506         /// 获取指定目录及子目录中所有子目录列表
507         /// </summary>
508         /// <param name="directoryPath">指定目录的绝对路径</param>
509         /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
510         /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
511         /// <param name="isSearchChild">是否搜索子目录</param>
512         public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
513         {
514             try
515             {
516                 if (isSearchChild)
517                 {
518                     return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
519                 }
520                 else
521                 {
522                     return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
523                 }
524             }
525             catch (IOException ex)
526             {
527                 throw ex;
528             }
529         }
530         #endregion
531 
532         #region 向文本文件写入内容
533 
534         /// <summary>
535         /// 向文本文件中写入内容
536         /// </summary>
537         /// <param name="filePath">文件的绝对路径</param>
538         /// <param name="text">写入的内容</param>
539         /// <param name="encoding">编码</param>
540         public static void WriteText(string filePath, string text, Encoding encoding)
541         {
542             //向文件写入内容
543             File.WriteAllText(filePath, text, encoding);
544         }
545         #endregion
546 
547         #region 向文本文件的尾部追加内容
548         /// <summary>
549         /// 向文本文件的尾部追加内容
550         /// </summary>
551         /// <param name="filePath">文件的绝对路径</param>
552         /// <param name="content">写入的内容</param>
553         public static void AppendText(string filePath, string content)
554         {
555             File.AppendAllText(filePath, content);
556         }
557         #endregion
558 
559         #region 将现有文件的内容复制到新文件中
560         /// <summary>
561         /// 将源文件的内容复制到目标文件中
562         /// </summary>
563         /// <param name="sourceFilePath">源文件的绝对路径</param>
564         /// <param name="destFilePath">目标文件的绝对路径</param>
565         public static void Copy(string sourceFilePath, string destFilePath)
566         {
567             File.Copy(sourceFilePath, destFilePath, true);
568         }
569         #endregion
570 
571         #region 将文件移动到指定目录
572         /// <summary>
573         /// 将文件移动到指定目录
574         /// </summary>
575         /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
576         /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
577         public static void Move(string sourceFilePath, string descDirectoryPath)
578         {
579             //获取源文件的名称
580             string sourceFileName = GetFileName(sourceFilePath);
581 
582             if (IsExistDirectory(descDirectoryPath))
583             {
584                 //如果目标中存在同名文件,则删除
585                 if (IsExistFile(descDirectoryPath + "\\" + sourceFileName))
586                 {
587                     DeleteFile(descDirectoryPath + "\\" + sourceFileName);
588                 }
589                 //将文件移动到指定目录
590                 File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName);
591             }
592         }
593         #endregion
594 
595 
596         #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
597         /// <summary>
598         /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
599         /// </summary>
600         /// <param name="filePath">文件的绝对路径</param>        
601         public static string GetFileNameNoExtension(string filePath)
602         {
603             //获取文件的名称
604             FileInfo fi = new FileInfo(filePath);
605             return fi.Name.Split('.')[0];
606         }
607         #endregion
608 
609         #region 从文件的绝对路径中获取扩展名
610         /// <summary>
611         /// 从文件的绝对路径中获取扩展名
612         /// </summary>
613         /// <param name="filePath">文件的绝对路径</param>        
614         public static string GetExtension(string filePath)
615         {
616             //获取文件的名称
617             FileInfo fi = new FileInfo(filePath);
618             return fi.Extension;
619         }
620         #endregion
621 
622         #region 清空指定目录
623         /// <summary>
624         /// 清空指定目录下所有文件及子目录,但该目录依然保存.
625         /// </summary>
626         /// <param name="directoryPath">指定目录的绝对路径</param>
627         public static void ClearDirectory(string directoryPath)
628         {
629             if (IsExistDirectory(directoryPath))
630             {
631                 //删除目录中所有的文件
632                 string[] fileNames = GetFileNames(directoryPath);
633                 for (int i = 0; i < fileNames.Length; i++)
634                 {
635                     DeleteFile(fileNames[i]);
636                 }
637 
638                 //删除目录中所有的子目录
639                 string[] directoryNames = GetDirectories(directoryPath);
640                 for (int i = 0; i < directoryNames.Length; i++)
641                 {
642                     DeleteDirectory(directoryNames[i]);
643                 }
644             }
645         }
646         #endregion
647 
648         #region 清空文件内容
649         /// <summary>
650         /// 清空文件内容
651         /// </summary>
652         /// <param name="filePath">文件的绝对路径</param>
653         public static void ClearFile(string filePath)
654         {
655             //删除文件
656             File.Delete(filePath);
657 
658             //重新创建该文件
659             CreateFile(filePath);
660         }
661         #endregion
662 
663         #region 删除指定目录
664         /// <summary>
665         /// 删除指定目录及其所有子目录
666         /// </summary>
667         /// <param name="directoryPath">指定目录的绝对路径</param>
668         public static void DeleteDirectory(string directoryPath)
669         {
670             if (IsExistDirectory(directoryPath))
671             {
672                 Directory.Delete(directoryPath, true);
673             }
674         }
675         #endregion
676     }

 

posted on 2015-07-08 15:25  勤劳的Coder  阅读(234)  评论(0编辑  收藏  举报