1 varAllfiles = Directory.GetFiles (@"D:\uploadpdf","*.csv");2 stringDataisnull =@"D:\dataisnull.txt";3 stringMatchlog =@"D:\matchLog.txt";4 foreach(varFilePathinchallfiles)5 {6DataTable dt =NewDataTable ();7FileStream FileStream =NewFileStream (FilePath, FileMode.Open, FileAccess.Read);8StreamReader StreamReader =NewStreamReader (fileStream);9 //record a row of records per readTen stringStrLine =string. Empty; One //record the contents of each field in each row of records A string[] Aryline =NULL; - string[] Tablehead =NULL; - //number of marked columns the intColumcount =0; - //indicates if the first line is read - BOOLIsFirst =true; -Console.Out.WriteLine (""); +StringBuilder Headbuilder =NewStringBuilder (); - //read data in CSV row by line + while((StrLine = StreamReader.ReadLine ())! =NULL) A { at if(IsFirst) - { -Tablehead = Strline.split (','); -IsFirst =false; -Columcount =tablehead.length; - //Create Columns in foreach(varHeadinchtablehead) - { toDataColumn column =NewDataColumn (head); + dt. Columns.Add (column); -Headbuilder.appendformat ("{0}\t\t\t", head); the } * if(Headbuilder.length! =0) $ {Panax Notoginseng using(StreamWriter SW =File.appendtext (matchlog)) - { the SW. WriteLine (Headbuilder.tostring ()); + } A } the } + Else - { $Aryline = Strline.split (','); $DataRow row =dt. NewRow (); - if(Aryline.length = =columcount) - { the for(inti =0; i < Columcount; i++) - {WuyiRow[i] =Aryline[i]; the } - } Wu dt. Rows.Add (row); - } About } $ if(Aryline! =NULL&& aryline.length >0) - { -Dt. Defaultview.sort = tablehead[0] +"ASC"; - } A streamreader.close (); + filestream.close (); the if(dt. Rows.Count = =0) - { $ //OutputLog (Dataisnull, String. Format ("{0} data is null.", FilePath)); the Continue; the } theStringBuilder Mpattributeslog =NewStringBuilder (); the - foreach(DataRow rowinchdt. Rows) in { the //var values = row. ItemArray; the //foreach (var head in Tablehead) About //{ the //Mpattributeslog.appendformat ("{0}\t\t\t", row[head]); the //} theMpattributeslog.append (string. Join ("\t\t\t", Row. ItemArray)); + if(Mpattributeslog.length! =0) - { the using(StreamWriter SW =File.appendtext (matchlog))Bayi { the SW. WriteLine (Mpattributeslog.tostring ()); the mpattributeslog.clear (); - } - } the } the}
Read/write CSV file