Filestream reads or writes files, and filestream reads and writes

Source: Internet
Author: User

Filestream reads or writes files, and filestream reads and writes

1 using System. IO; // reference System. IO 2 namespace filestream 3 {4 public partial class Form1: Form 5 {6 public Form1 () 7 {8 InitializeComponent (); 9} 10 11 private void btnWrite_Click (object sender, eventArgs e) 12 {13 SaveFileDialog sfd = new SaveFileDialog (); 14 15 sfd. filter = "text file | *. txt | c # file | *. cs "; 16 17 if (sfd. showDialog () = System. windows. forms. dialogResult. OK) 18 {19 txtPath. text = sfd. fileName; // saved path 20 using (FileStream fs = new FileStream (txtPath. text, FileMode. create) 21 {22 string txt = txtContent. text; 23 byte [] buffer = Encoding. UTF8.GetBytes (txt); 24 fs. write (buffer, 0, buffer. length); 25} 26} 27} 28 29 private void btnRead_Click (object sender, EventArgs e) 30 {31 OpenFileDialog ofd = new OpenFileDialog (); 32 ofd. filter = "text file | *. txt "; 33 if (ofd. showDialog () = System. windows. forms. dialogResult. OK) 34 {35 txtPath. text = ofd. fileName; 36 using (FileStream fs = new FileStream (txtPath. text, FileMode. open) 37 {38 // byte [] buffer = new byte [fs. length]; 39 // fs. read (buffer, 0, buffer. length); 40 41 // string msg = Encoding. UTF8.GetString (buffer); 42 // txtContent. text = msg; 43 44 45 using (StreamReader sr = new StreamReader (fs, Encoding. UTF8) 46 {47 string msg = sr. readToEnd (); 48 txtContent. text = msg; 49} 50} 51} 52} 53} 54}

 

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.