1 public class FileHelper 2 { 3 ///4 /// 获取指定路径下所有文件 5 /// 6 public static ListGetFiles(string path) 7 { 8 //using System.IO; 9 if (!Directory.Exists(path)) //路径不存在10 return null; 11 List result = new List (); 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 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 /// 35 /// 获取指定文件内容36 /// 注:这里适用于读取文本类型文件37 /// 38 public static ListGetTxtFileContent(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 result = new List ();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 /// 56 /// 删除指定文件57 /// 58 public static void DeleteFile(string fileName)59 {60 File.Delete(fileName);61 }62 63 ///64 /// 创建文件65 /// 66 /// 文件全路径67 /// 写入内容68 public static void CreateFile(string fileName,Listcontent=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 }