C # Byte [] array reading and writing files,
I used asp.net to build this project. The Code is as follows:
1 protected void ByteToString_Click (object sender, EventArgs e) 2 {3 4 5 string content = this.txt Content. text. toString (); 6 7 if (string. isNullOrEmpty (content) 8 {9 return; 10} 11 12 // convert string to byte array 13 byte [] array = Encoding. UTF8.GetBytes (content); 14 15 // convert the byte array to string16 string result = Encoding. UTF8.GetString (array); 17 18 19 Response. write (result); 20 21 22} 23 // use byte [] array to Write to file 24 protected void writerFile_Click (object sender, EventArgs e) 25 {26 27 string content = this.txt Content. text. toString (); 28 29 if (string. isNullOrEmpty (content) 30 {31 return; 32} 33 34 // convert string to byte array 35 byte [] array = Encoding. UTF8.GetBytes (content); 36 37 string path = Server. mapPath ("/test.txt"); 38 // create a file stream 39 FileStream fs = new FileStream (path, FileMode. create); 40 41 // write the byte array to the file 42 fs. write (array, 0, array. length); 43 // close the stream for all stream types; otherwise, memory leakage occurs. 44 fs. close (); 45 46 Response. write ("saved file succeeded"); 47 48 49} 50 // Read File 51 protected void readFile_Click (object sender, EventArgs e) using byte [] Array) 52 {53 string path = Server. mapPath ("/test.txt"); 54 55 FileStream fs = new FileStream (path, FileMode. open); 56 57 // get the file size 58 long size = fs. length; 59 60 byte [] array = new byte [size]; 61 62 // read the object to 63 fs in the byte array. read (array, 0, array. length); 64 65 fs. close (); 66 67 // convert byte array to string68 string result = Encoding. UTF8.GetString (array); 69 70 71 Response. write (result); 72 73 74 75}