C # Byte [] array reading and writing files,

Source: Internet
Author: User

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}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.