Fork me on GitHub

青禹小生

雁驰万里却作禽,鱼未得水空有鳞。 花开花落花不语,昨是昨非昨亦今。

导航

C#文件流读写文件的简单winform实现

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.IO;
 7 using System.Linq;
 8 using System.Text;
 9 using System.Threading.Tasks;
10 using System.Windows.Forms;
11 
12 namespace one
13 {
14     public partial class Form1 : Form
15     {
16         public Form1()
17         {
18             InitializeComponent();
19         }
20 
21         private void btnOpen_Click(object sender, EventArgs e)
22         {
23             using (OpenFileDialog ofd = new OpenFileDialog())
24             {
25                 if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
26                 {
27                     return;
28                 }
29 
30             using (FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read))
31                 {
32                     using (StreamReader sr = new StreamReader(fs,Encoding.Default))
33                     {
34                         while (!sr.EndOfStream)
35                         {
36                             string line = sr.ReadLine();
37                             this.txtContent.Text += line;
38                         }
39                         sr.Close();
40                     }
41                     fs.Close();
42                     fs.Dispose();
43                 }
44             }
45         }
46 
47         private void btnSave_Click(object sender, EventArgs e)
48         {
49             using (SaveFileDialog sfd = new SaveFileDialog())
50             {   
sfd.DefaultExt = "txt";
                sfd.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
51 if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) 52 { 53 return; 54 } 55 using (FileStream fs = new FileStream(sfd.FileName, FileMode.OpenOrCreate, FileAccess.Write)) 56 { 57 string txt = txtContent.Text.Replace("\n","\r\n"); 58 byte[] data = Encoding.UTF8.GetBytes(txt); 59 fs.Write(data, 0, data.Length); 60 fs.Close(); 61 fs.Dispose(); 62 } 63 } 64 } 65 } 66 }

 

posted on 2015-12-04 16:27  司徒道  阅读(1272)  评论(0编辑  收藏  举报