标签:
以下代码是C#对文件的写入和删除的操作:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 EmployeeDAL DAL = new EmployeeDAL(); 6 List<Sys_Employee> list = DAL.GetAll().ToList(); 7 WriteTxt(list); 8 //DeleDirFile(); 9 } 10 11 #region 对文件的操作 12 13 //写文件 14 public static void WriteTxt(List<Sys_Employee> Emp) 15 { 16 string path = @"F:\CreateDirTxt"; 17 18 if (!Directory.Exists(path)) 19 { 20 Directory.CreateDirectory(path); 21 } 22 foreach (var emp in Emp) 23 { 24 //创建文件流 25 FileStream Stream = new FileStream(@"F:\CreateDirTxt\" + emp.EmpName + "信息文本.txt", FileMode.Create); 26 StreamWriter Writer = new StreamWriter(Stream); 27 //向流中写入内容 28 Writer.Write(string.Format("姓名是:{0} \n性别是:{1} \n地址是:{2}", emp.EmpName, (emp.EmpSex == 0) ? "男" : "女", emp.EmpAddress)); 29 //清空缓存 30 Writer.Flush(); 31 //关闭 32 Writer.Close(); 33 Console.WriteLine("正在创建 " + emp.EmpName + " 的信息文本"); 34 } 35 Console.WriteLine("创建完成 O(∩_∩)O"); 36 Console.ReadLine(); 37 } 38 //删文件 39 public static void DeleDirFile() 40 { 41 string path = @"F:\CreateDirTxt\"; 42 if (Directory.Exists(path)) 43 { 44 //获得文件夹数组 45 string[] Directorlenght = Directory.GetDirectories(path); 46 //获得文件数组 47 string[] filelength = Directory.GetFiles(path); 48 //遍历删除文件夹 49 foreach (string lst in Directorlenght) 50 { 51 Directory.Delete(lst); 52 } 53 //遍历删除文件 54 foreach (string lst in filelength) 55 { 56 int Index = lst.LastIndexOf("\\") + 1; 57 string EmpName = lst.Substring(Index, lst.Length - Index); 58 File.Delete(lst); 59 Console.WriteLine("文件 -"+EmpName+"- 删除成功"); 60 } 61 Console.WriteLine("完成! O(∩_∩)O"); 62 } 63 else 64 { 65 Console.WriteLine("文件或者文件夹不存在,请重新查看"); 66 } 67 Console.ReadLine(); 68 } 69 #endregion 113 }
标签:
原文地址:http://www.cnblogs.com/wwj1992/p/5077227.html