C# 读写文件
介绍一下C#的文件操作方法。
1. TXT文件
写入
//using会自动关闭StreamWriter using (StreamWriter sw = new StreamWriter("TestFile.txt")) { sw.Write("This is the "); sw.WriteLine("header for the file."); sw.WriteLine("-------------------"); sw.Write("The date is: "); sw.WriteLine(DateTime.Now); }
2. CSV文件
写入
与txt的写出方法一样,唯一的区别是txt列之间是用"\t"分割,csv用"," 。
using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.Default)) { string repStr = ","; string colHead = string.Empty; for (int i = 1; i < dataTable.Columns.Count-2; i++) { colHead += dataTable.Columns[i].ColumnName + repStr; } if (colHead.Contains(repStr)) { colHead = colHead.Remove(colHead.LastIndexOf(repStr)); } sw.WriteLine(colHead); for (int i = 0; i < dataTable.Rows.Count; i++) { int cell = dataTable.Rows[i].ItemArray.Count()-2; string content = string.Empty; for (int j = 1; j < cell; j++) { content += dataTable.Rows[i][j] + repStr; } if (content.Contains(repStr)) { content = content.Remove(content.LastIndexOf(repStr)); } sw.WriteLine(content); } }