zoukankan      html  css  js  c++  java
  • 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(" "," "); 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 }
  • 相关阅读:
    xml文档格式学习笔记
    Visual Studio学习记录
    Java学习笔记
    C#项目学习记录
    Linux命令行与shell脚本编程大全 学习笔记
    NodeJS (npm) 学习笔记
    Angular学习笔记
    TypeScript学习笔记
    java 项目相关 学习记录
    docker学习记录
  • 原文地址:https://www.cnblogs.com/laresh/p/5019672.html
Copyright © 2011-2022 走看看