• 练习:WinForm 对话框控件(文件读取、写入)


    设计界面:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using System.Text;
    
    namespace 对话框
    {
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
    
            #region 读取数据
            private void button2_Click(object sender, EventArgs e)
            {
                //显示工具
                DialogResult dr = openFileDialog1.ShowDialog();
    
                //取值
                if (dr == DialogResult.OK)
                {
                    //文件路径
                    string path = openFileDialog1.FileName;
    
                    //文件流
                    FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read);
    
                    //读取
                    byte[] sj=new byte[fs.Length]; //造一个二进制数组,用来存储读到的数据
                    
                    fs.Read(sj,0,sj.Length); //将文件读取为二进制数据,并且放到二进制数组里边
    
                    //将二进制数据转为字符串
                    richTextBox1.Text = Encoding.Default.GetString(sj);
    
                    //关闭流
                    fs.Close();
                }
            }
            #endregion
    
            #region 写入数据
            private void button1_Click(object sender, EventArgs e)
            {
                //显示选择文件对话框
                DialogResult dr=saveFileDialog1.ShowDialog();
                
                //获取路径
                if (dr == DialogResult.OK)
                {
                    string path = saveFileDialog1.FileName;   //文件路径
                    string nr = richTextBox1.Text; //取出文本框中的内容
                    byte[] sj = Encoding.Default.GetBytes(nr);  //将字符串转为二进制数组
    
                    //造文件流
                    FileStream fs = new FileStream(path,FileMode.Create);
    
                    //向文件里边写数据
                    fs.Write(sj,0,sj.Length);
    
                    //关闭流
                    fs.Close();
                }
            }
            #endregion
        }
    }

  • 相关阅读:
    使用片段嵌入进行文档搜索
    详解支持向量机
    使用NLP检测和对抗AI生成的假新闻
    Detectron2 API 之 config | 十五
    用Python可视化卷积神经网络
    六种用于文本分类的开源预训练模型
    解空间树(回溯算法,分支界限法)
    日记2
    C编程(C语言程序设计,大连理工大学MOOC)
    编程题(C/C++程序设计,同济大学mooc)
  • 原文地址:https://www.cnblogs.com/xiao55/p/5831270.html
Copyright © 2020-2023  润新知