Namespace file { class MyFile { string FilePath; byte[] Bydata = new byte[100]; public char[] MyData = new char[1000]; public string reslutstr = null; public MyFile () {} Public MyFile (string path) { FilePath = path; } public void ReadFile1 () { Try { FileStream file = new fileStream (FilePath, FileMode.Open); file. Seek (0, Seekorigin.begin); file. Read (bydata, 0, 100); 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, MyData, 0); //console.writeline ( MyData); foreach (char ch in MyData) { &nBsp RESLUTSTR + = ch. ToString (); } file. Close (); } catch (IOException e) { Console.WriteLine (E. ToString ()); } } public void ReadFile2 () { StreamReader sr = new StreamReader (FilePath, Encoding.default); String Line; while (line = Sr. ReadLine ()) = null) { Reslutstr + = line; // Console.WriteLine (line. ToString ()); } } public void SaveFile1 (string savestr) { FileStream fs = new FileStream (FilePath, FileMode.Create); //Get byte array byte[] data = System.Text.Encoding.Default.GetBytes (SAVESTR); //Start writing FS. Write (data, 0, data. Length); //emptying buffers, closing streams FS. Flush (); FS. Close (); } public void SaveFile2 () { FileStream fs = new FileStream (FilePath, FileMode.Create); StreamWriter sw = new StreamWriter (FS); //start writing SW. Write ("Hello world!!!!"); //emptying buffer SW. Flush (); //Close Flow SW. Close (); FS. Close (); }
} }
Call Method:
MyFile MyFile = new MyFile (Filepath); string result = NULL; Myfile.savefile1 (SAVASTR); Myfile.savefile2 (); Myfile.readfile2 ();
C # TXT file read and write