1. Use FileStream to read and write files
To add a namespace reference:
using System; using System.Collections.Generic; using System.Text; using System.IO;
To read the core code:
byte[] Bydata =New byte[ -];Char[] Chardata =New Char[ +];Try{FileStream SFile=NewFileStream ("file path", FileMode.Open); Sfile.seek ( -, Seekorigin.begin); //The first parameter is a byte array that is passed in to accept the data from the FileStream object, and the 2nd parameter is the byte//The position in the array where the data is to be written, usually 0, which indicates that the data is written to the array from the beginning file of the array,//The last parameter specifies how many characters to read from a file.Sfile.read (Bydata,0, -); }Catch(IOException e) {Console.WriteLine ("An IO exception have been thrown!"); Console.WriteLine (E.tostring ()); Console.ReadLine (); return;} Decoder D=Encoding.UTF8.GetDecoder ();d. GetChars (Bydata,0, Bydata.length, Chardata,0); Console.WriteLine (Chardata); Console.ReadLine ();
Write the core code:
New FileStream (file path, filemode.create); // get byte array byte [] data =new utf8encoding (). GetBytes (String); // begins writing to FS. Write (data,0, data. Length); // empties the buffer, closes the stream FS. Flush (); fs. Close ();
2. use StreamReader and StreamWriter to read and write files
StreamReader Read file:
New StreamReader (file path); string sline=""newwhilenull) { = objReader.ReadLine (); if null&&!sline.equals ("")) Linelist.add (sline);} Objreader.close (); return LineList;
StreamWriter Write files:
FileStream fs = new FileStream (file path, filemode.create);
StreamWriter SW =NewStreamWriter (FS, System.Text.Encoding.GetEncoding ("GB2312"));//support for Chinese characters can be achieved by specifying character encoding, otherwise garbled if you open the view with NotepadSW. Flush ();if(checkfile) {sw. Basestream.seek (0, seekorigin.end);//Move to end}Else{SW. Basestream.seek (0, Seekorigin.begin);}stringtemp ="write something, whatever ."; SW. WriteLine (temp); SW. Flush (); SW. Close ();
Fs. Close ();
C # Read and write files