1 public class FileHelper
2 {
3 /// <summary>
4 /// 获取指定路径下所有文件
5 /// </summary>
6 public static List<string> GetFiles(string path)
7 {
8 //using System.IO;
9 if (!Directory.Exists(path)) //路径不存在
10 return null;
11 List<string> result = new List<string>();
12 DirectoryInfo dir = new DirectoryInfo(path);
13 DirectoryInfo[] subfolder = dir.GetDirectories();
14 if (subfolder != null&&subfolder.Length>0)
15 {
16 foreach(DirectoryInfo item in subfolder)
17 {
18 List<string> subFiles = GetFiles(item.FullName); //FullName:完整路径
19 if (subFiles != null && subFiles.Count > 0)
20 result.AddRange(subFiles);
21 }
22 }
23 FileInfo[] files = dir.GetFiles();
24 if(files!=null)
25 {
26 foreach(FileInfo file in files)
27 {
28 result.Add(file.FullName);
29 }
30 }
31 return result;
32 }
33
34 /// <summary>
35 /// 获取指定文件内容
36 /// 注:这里适用于读取文本类型文件
37 /// </summary>
38 public static List<string> GetTxtFileContent(string fileName)
39 {
40 if (!File.Exists(fileName)) //文件不存在
41 return null;
42 FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
43 StreamReader reader = new StreamReader(fs, Encoding.Default);
44 List<string> result = new List<string>();
45 string line = "";
46 while((line=reader.ReadLine())!=null)
47 {
48 result.Add(line);
49 }
50 reader.Close();
51 fs.Close();
52 return result;
53 }
54
55 /// <summary>
56 /// 删除指定文件
57 /// </summary>
58 public static void DeleteFile(string fileName)
59 {
60 File.Delete(fileName);
61 }
62
63 /// <summary>
64 /// 创建文件
65 /// </summary>
66 /// <param name="path">文件全路径</param>
67 /// <param name="content">写入内容</param>
68 public static void CreateFile(string fileName,List<string> content=null)
69 {
70 if(!File.Exists(fileName))
71 {
72 FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
73 if (content != null && content.Count > 0)
74 {
75 StreamWriter sw = new StreamWriter(fs);
76 foreach (string line in content)
77 {
78 sw.WriteLine(line);
79 }
80 sw.Close();
81 }
82 fs.Close();
83 }
84 }
85
86 }