c#winform制作记事本

该文章描述了一个简单的文本编辑器的实现,利用C#的System.IO命名空间的StreamReader和StreamWriter类进行文件的读写操作。在WindowsForms环境下创建用户界面,通过TextBox控件显示和输入文本,按钮触发读写文件功能。当用户提交文件名后,程序会检查文件是否存在,如果存在则读取内容显示,否则创建新文件。提交文件内容时,将TextBox中的文本写入指定文件。
摘要由CSDN通过智能技术生成

实现功能:编辑文件

用到的命名空间:

System  //这个不用解释了吧

System.IO //系统的各种流(stream)

System.Windows.Forms //winform

System.Drawing //绘图

读文件用System.IO下的StreamReader,写文件用StreamWrtier

实现流程

先用winform做一个界面:

    class Form1:Form{
        public Form1(){
            inittext();
        }
        public TextBox t = new TextBox();
        public TextBox t2 = new TextBox();
        public Button b = new Button();
        public Button b2 = new Button();
        public void inittext(){
            t.Text = "text";
            t.Multiline = true;
            t.ScrollBars = ScrollBars.Vertical;
            t.Size = new Size(400,500); 
            Controls.Add(t);
            t2.Text = "请输入文件名";
            t2.Top = 0;
            t2.Left = 401;
            Controls.Add(t2);
            b.Top = 20;
            b.Left = 401;
            b.Text = "提交文件名";
            b.Click += btnclick;
            Controls.Add(b);
            b2.Top = 40;
            b2.Left = 401;
            b2.Size = new Size(100,20);
            b2.Text = "提交文件内容";
            b2.Click += btnclick2;
            Controls.Add(b2);
        }
    class m{
        static void Main(){
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form1 f = new Form1();
            f.Size = new Size(600,600);
            f.Text = "记事本";
            Application.Run(f);
        }

判断文件名是否为空,如果不是,判断是否有此文件,有则将t设置为文件内容,没有则新建

        public void btnclick(object sender,EventArgs e){
            if(t2.Text != ""){
                if(File.Exists(t2.Text)){
                    StreamReader sr = new StreamReader(t2.Text);
                    if(sr != null){
                        string s = sr.ReadLine();
                        string context = "";
                        while(s != null){
                            context += s;
                            s = sr.ReadLine();
                        }
                        t.Text = context;
                        sr.Close();
                    }
                }else{
                    StreamWriter sr = new StreamWriter(t2.Text);
                    sr.Close();
                }
            }
        }

提交文件内容,写入

        public void btnclick2(object sender,EventArgs e){
            StreamWriter sr = new StreamWriter(t2.Text);
            char[] c = t.Text.ToCharArray();
            sr.Write(c);
            sr.Close();
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值