文件操作3(编辑器例子)

file类方法

首先加入几个控件,两个分组空间,一个文本框,三个按钮,一个richTextBox控件,用于写入信息,布局如下:
窗体布局

下面是代码:

 //保存文件路径的全局变量
        private static string Depath = "";

首先创建文件

  if (textBox1.Text.Length < 0)
            {
                MessageBox.Show("输入文件信息");
            }
            else
            {

                Depath = @"" + textBox1.Text.Trim() + "";
                if (File.Exists(Depath)) MessageBox.Show("文本文件已存在,请重新命名");
                else
                {
                    StreamWriter sw = File.CreateText(Depath);
                    MessageBox.Show("文件已创建");
                    sw.Close();
                }
            }

保存文件信息

  Depath = textBox1.Text.Trim();
            FileStream file = File.Open(Depath,FileMode.OpenOrCreate,FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(file,Encoding.UTF8);
            sw.Write(richTextBox1.Text.ToString());
            MessageBox.Show("文件写入成功");

            sw.Close();

打开文件编辑框,这里用到OpenFileDialog,代码如下:

 try
            {
                //打开文件对话框
                OpenFileDialog op = new OpenFileDialog();
                op.Title = "打开文本文件";
                op.FileName = "";
                op.AddExtension = true;//检查文件扩展名
                op.CheckFileExists = true;//指定文件是否存在
                op.CheckPathExists = true;//检测路径合法性
                op.Filter = "文本文件(*.txt)|*.txt";
                op.ValidateNames = true;//接受有效的文件名
                //判断是否点击了确定按钮
                if (op.ShowDialog() == DialogResult.OK) {
                    StreamReader sr = new StreamReader(op.FileName,Encoding.Default);
                    this.richTextBox1.Text = sr.ReadToEnd();
                   textBox1.Text  = op.FileName;

                    sr.Close();
               }
                MessageBox.Show("文件打开成功");

            }
            catch (Exception e1)
            {

                MessageBox.Show("错误"+e1.ToString());
            }

好了,简单的小示例基本完成,但要注意一点,每做完一个文件操作都必须把读写器关闭,否则会提示进程占用;
**上述代码还需注意一点,容易忘记;当打开文件时候,要把路径变量赋值,即

 textBox1.Text  = op.FileName;
     Depath = textBox1.Text.Trim();

不然保存编辑的文本时 Depath是空值;**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值