usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;namespacecommonlib{/// <summary> ///read and write files/// </summary> Public classFilehelper {/// <summary> ///use the FileStream class to read the file, convert it to a char array, and then output/// </summary> Public voidRead () {Try { byte[] Bydata =New byte[ -]; Char[] Chardata =New Char[ +]; FileStream file=NewFileStream ("E:\\test.txt", FileMode.Open); File. Seek (0, Seekorigin.begin); File. Read (Bydata,0, -); //bydata A byte array to accept the data from the FileStream object, the 2nd parameter is the position in the byte array where the data is written, usually 0, which indicates that the data is written to the array from the beginning file of the array, and the last parameter specifies how many characters to read from the file.Decoder d =Encoding.Default.GetDecoder (); D.getchars (Bydata,0, Bydata.length, Chardata,0); Console.WriteLine (Chardata); File. Close (); } Catch(IOException e) {Console.WriteLine (e.tostring ()); } } /// <summary> ///use StreamReader to read the file, and then one line of output/// </summary> /// <param name= "path" ></param> Public voidRead (stringpath) {StreamReader SR=NewStreamReader (path, encoding.default); String Line; while(line = Sr. ReadLine ())! =NULL) {Console.WriteLine (line. ToString ()); } } /// <summary> ///use the FileStream class to create a file and then write the data to a file/// </summary> Public voidWrite () {FileStream fs=NewFileStream ("E:\\ak.txt", FileMode.Create); //get byte array byte[] data = System.Text.Encoding.Default.GetBytes ("Hello world!"); //Start WritingFs. Write (data,0, data. Length); //empties the buffer, closes the streamFS. Flush (); Fs. Close (); } /// <summary> ///use the FileStream class to create a file, use the StreamWriter class, write data to a file/// </summary> /// <param name= "path" ></param> Public voidWrite (stringpath) {FileStream FS=NewFileStream (path, filemode.create); StreamWriter SW=NewStreamWriter (FS); //Start WritingSw. Write ("Hello World!!!!"); //emptying buffersSW. Flush (); //Close the streamSW. Close (); Fs. Close (); } }}
C # Read and write TXT file