Reprint Please specify source: http://www.cnblogs.com/ntotl/p/5152727.html
Using file:
1 if (File.exists (importpath)) 2 {3 string readText = File.readalltext (importpath); // The result of the read contains \ r \ n 4 string [] LineList1 =5 }
View Code
Read with StreamReader:
1list<string> lineList2 =Newlist<string>(); 2 //ArrayList linesList2 = new ArrayList ();//3 4StreamReader sr =NewStreamReader (importpath);5 stringOneline = Sr. ReadLine ();//Read Current line6 7 while(!Sr. Endofstream)8 {9 Linelist2.add (Sr. ReadLine ());Ten } One Sr. Close (); A - if(Linelist2.count >0) - { the for(inti =0; i < Linelist2.count; i++) - { - stringline =Linelist2[i]. ToString (); - stringRegex =", |,|\\s+"; + string[] split =Regex.Split (line, Regex); - } +}
View Code
ArrayList and List<string> are mentioned here; record it to learn
Http://zhidao.baidu.com/link?url=WwkEzOGYRxGeU0n0n4xsp5ROJDD6cKMwKhCRC_A7hwe6WnrATRwwye6aUQ0wJthEn0q3vRq704F53usl3OfH-a
Write with Filsstream:
1 stringExportPath1 ="F:\\upload\\readandwritefile\\streamreader1.txt";2FileStream FS1 =NewFileStream (exportPath1, filemode.openorcreate);3 byte[] data =NewUTF8Encoding (). GetBytes ("AAAA");4FS1. Write (data,0, data. Length);5 FS1. Flush ();6FS1. Close ();
View Code
Write with StreamWriter:
1 #regionConstruct Data DT2DataTable dt =NewDataTable ();3Dt. Columns.Add ("player");4Dt. Columns.Add ("Race");5DataRow row =NULL;6 for(inti =0; I <5; i++)7 {8row =dt. NewRow ();9row["player"] ="name_"+i;Tenrow["Race"] ="Race_"+i; One dt. Rows.Add (row); A } - #endregion - the stringExportPath2 ="F:\\upload\\readandwritefile\\streamreader2.txt"; -FileStream FS2 =NewFileStream (ExportPath2, filemode.openorcreate); -StreamWriter SW2 =NewStreamWriter (FS2); -StringBuilder SB =NewStringBuilder (); +Sb. Append ("player race \ r \ n"); - foreach(DataRow Drinchdt. Rows) + { ASb. Append (dr["player"] +" "+ dr["Race"] +"\ r \ n"); at } - SW2. Write (SB); - SW2. Flush (); - SW2. Close (); -FS2. Close ();
View Code
Because I just graduated soon, is mainly engaged in the development of ASP, so the above code after reading also processed, is convenient to write to the database, export is also so, can be used to back up data to TXT file.
I am still in the learning stage, if there is understanding or code errors, please also advise.
Several ways to read and write C # files