C# Windows桌面应用 ---- 实例:文件读写

实例题目:对输入的账号、姓、名、余额信息保存到文件,并可以读取到界面。

演示:
在这里插入图片描述
创建三个项目文件:
在这里插入图片描述
设计思路:
由于读和写的界面差不多,就是按钮button不一样,这样的话,可以做一个父亲窗体,让读和写两个窗体继承父窗体即可(关键操作)。
对于数据的操作,可以将数据封装起来,这样更符合面向对象的编程,下面创建了Record类。

一个关键操作:
不在同一个项目的类不能直接继承!!!
需要如下操作:

  1. 将BankUIForm项目右击属性,设置它的输出类型为类库;
  2. 右击BankUIForm项目点生成(每次修改都要重新生成);
  3. 将BankUIForm类库分别引用到ReaderForm和WriterForm项目中(打开项目,右击引用);在这里插入图片描述

一、BankUIForm项目

Record 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文件与流
{
    public class Record // 这里需要设置访问属性问public 不然后面会访问不了
    {
        // 四个纪录属性
        public int Account { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public decimal Balance { get; set; }
        // 构造函数
        public Record()
            :this(0,string.Empty,string.Empty,0m)
        { }
        // 构造函数
        public Record(int account,string firstName,string lastName,decimal balance)
        {
            Account = account;
            FirstName = firstName;
            LastName = lastName;
            Balance = balance;
        }
    }
}

BankUIForm窗体(父亲)的代码

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 文件与流
{
    public partial class BankUIForm : Form
    {
        public BankUIForm()
        {
            InitializeComponent();
        }
        public void Form1_Load(object sender, EventArgs e)
        {}
        // 获取 窗体Textbox控件内容,保存在record返回
        public Record GetTextBoxText()
        {
            Record record = new Record(Int32.Parse(accountTextBox.Text), firstnameTextBox.Text, lastnameTextBox.Text, Decimal.Parse(balanceTextBox.Text));
            return record;
        }
        // 设置 窗体Textbox控件内容
        public void SetTextBoxText(Record record)
        {
            accountTextBox.Text = record.Account.ToString();
            firstnameTextBox.Text = record.FirstName;
            lastnameTextBox.Text = record.LastName;
            balanceTextBox.Text = record.Balance.ToString();
        }
        // 清空 窗体Textbox控件内容
        public void ClearTextBox()
        {
            foreach (Control control in Controls)
            {
                if(control is TextBox)
                {
                    ((TextBox)control).Clear();
                }
            }
        }
    }
}

二、WriterForm项目:继承BankUIForm窗体,写文本

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 文件与流;
using System.IO;

namespace WriterForm
{
    public partial class writerForm : 文件与流.BankUIForm
    {
        public writerForm()
        {
            InitializeComponent();
        }
        FileStream filestream; // 文件流对象:水池
        StreamWriter streamwriter;  // 写入流:水管
        // 打开文件
        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult result; // 纪录窗体返回值
            string fileName; //纪录文件名
            // 创建打开文件保存窗体
            using (SaveFileDialog saveFile = new SaveFileDialog())
            {
                saveFile.CheckFileExists = false;
                result = saveFile.ShowDialog();
                fileName = saveFile.FileName;
            }
            // 判断是否点了确定,如果是则进入
            if(result== DialogResult.OK)
            {
                if (fileName == null)
                {
                    MessageBox.Show("文件名不能为空!");
                }
                // 文件名不为空
                else
                {
                    try
                    {
                        // 创建文件流
                        filestream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
                        // 写流连接池塘
                        streamwriter = new StreamWriter(filestream);
                        enterButton.Enabled = true;
                        saveButton.Enabled = false;

                    }
                    catch (Exception exp)
                    {
                        MessageBox.Show("文件写入出错!",exp.Message);
                    }
                }
            }
        }
        // 写入数据
        private void enterButton_Click(object sender, EventArgs e)
        {
            try
            {
                // 将窗体正确数据写入文本
                Record record=GetTextBoxText();
                streamwriter.WriteLine("{0},{1},{2},{3}", record.Account, record.FirstName, record.LastName, record.Balance);
            }
            catch (Exception)
            {
                MessageBox.Show("填写格式错误!"); ;
            }
            ClearTextBox(); // 清空textbox控件内容
        }
        //  结束输入,关闭文件流,程序退出
        private void exitButton_Click(object sender, EventArgs e)
        {
            streamwriter.Close();
            Application.Exit();
        }
    }
}

三、ReaderForm项目:继承BankUIForm窗体,读文件

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using 文件与流;

namespace ReadForm
{
    public partial class ReaderFoem : 文件与流.BankUIForm
    {
        public ReaderFoem()
        {
            InitializeComponent();
        }
        FileStream filestream; // 文件流对象 :水池
        StreamReader streamreader; // 文件读对象:水管
        //  打开文件
        private void readButton_Click(object sender, EventArgs e)
        {
            DialogResult result; // 纪录按钮结果
            string fileName; // 文件名
            // 创建文件打开窗体
            using (OpenFileDialog openfile=new OpenFileDialog())
            {
                result = openfile.ShowDialog(); // 返回结果
                fileName = openfile.FileName; //纪录文件名
            }
            // 如果按了确定按钮
            if(result== DialogResult.OK)
            {
                try
                {
                    if (fileName == null) 
                    {
                        MessageBox.Show("文件名不能为空!");
                    }
                    // 文件名不为空时,开始读文件
                    else
                    {
                        // 创建文件流对象,池塘
                        filestream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                        // 创建读对象,连接池塘
                        streamreader = new StreamReader(filestream);
                        nextButton.Enabled = true;
                        readButton.Enabled = false;
                    }
                }
                catch (Exception) // 捕获异常
                {
                    MessageBox.Show("打开文件失败!");
                }
            }
        }
        // 点击下一条按钮
        private void nextButton_Click(object sender, EventArgs e)
        {
            string str; // 保存所读取的一行数据字符串
            string[] values; // 保存4项数据
            try
            {
                str = streamreader.ReadLine(); // 读数据
                // 文件读完,关闭流对象
                if(str==null)
                {
                    streamreader.Close(); 
                    readButton.Enabled = true; // 此文件读取完成,可以继续读取下一个文件
                    nextButton.Enabled = false;
                    ClearTextBox();
                    MessageBox.Show("文件读完 !");
                }
                else
                {
                    // 将数据显示在窗体上
                    values = str.Split(',');
                    Record record = new Record(Int32.Parse(values[0]), values[1], values[2], Decimal.Parse(values[3]));
                    SetTextBoxText(record);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("文件读写错误!");
            }
        }
        // 退出按钮
        private void exitButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

萤火虫的光点虽然微弱,但亮着便是向黑暗挑战

关注微信公众号:码农云库

进步需要交流 !!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章