标签:
1 var allFiles = Directory.GetFiles(@"D:\uploadpdf", "*.csv"); 2 string dataIsNull = @"D:\dataisnull.txt"; 3 string matchLog = @"D:\matchLog.txt"; 4 foreach (var filePath in allFiles) 5 { 6 DataTable dt = new DataTable(); 7 FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); 8 StreamReader streamReader = new StreamReader(fileStream); 9 //记录每次读取的一行记录 10 string strLine = string.Empty; 11 //记录每行记录中的各字段的内容 12 string[] aryLine = null; 13 string[] tableHead = null; 14 //标示列数 15 int columCount = 0; 16 //标示是否是读取的第一行 17 bool isFirst = true; 18 Console.Out.WriteLine(""); 19 StringBuilder headBuilder = new StringBuilder(); 20 //逐行读取CSV中的数据 21 while ((strLine = streamReader.ReadLine()) != null) 22 { 23 if (isFirst) 24 { 25 tableHead = strLine.Split(‘,‘); 26 isFirst = false; 27 columCount = tableHead.Length; 28 //创建列 29 foreach (var head in tableHead) 30 { 31 DataColumn column = new DataColumn(head); 32 dt.Columns.Add(column); 33 headBuilder.AppendFormat("{0}\t\t\t", head); 34 } 35 if (headBuilder.Length != 0) 36 { 37 using (StreamWriter sw = File.AppendText(matchLog)) 38 { 39 sw.WriteLine(headBuilder.ToString()); 40 } 41 } 42 } 43 else 44 { 45 aryLine = strLine.Split(‘,‘); 46 DataRow row = dt.NewRow(); 47 if (aryLine.Length == columCount) 48 { 49 for (int i = 0; i < columCount; i++) 50 { 51 row[i] = aryLine[i]; 52 } 53 } 54 dt.Rows.Add(row); 55 } 56 } 57 if (aryLine != null && aryLine.Length > 0) 58 { 59 dt.DefaultView.Sort = tableHead[0] + " asc"; 60 } 61 streamReader.Close(); 62 fileStream.Close(); 63 if (dt.Rows.Count == 0) 64 { 65 //OutputLog(dataIsNull, string.Format("{0} data is null.", filePath)); 66 continue; 67 } 68 StringBuilder mpAttributesLog = new StringBuilder(); 69 70 foreach (DataRow row in dt.Rows) 71 { 72 //var values = row.ItemArray; 73 //foreach (var head in tableHead) 74 //{ 75 // mpAttributesLog.AppendFormat("{0}\t\t\t", row[head]); 76 //} 77 mpAttributesLog.Append(string.Join("\t\t\t", row.ItemArray)); 78 if (mpAttributesLog.Length != 0) 79 { 80 using (StreamWriter sw = File.AppendText(matchLog)) 81 { 82 sw.WriteLine(mpAttributesLog.ToString()); 83 mpAttributesLog.Clear(); 84 } 85 } 86 } 87 }
标签:
原文地址:http://www.cnblogs.com/xiangzhe-C/p/zlyang_CSV.html