OpenWrite方法打开现有文件并进行写入

Posted on 2019-01-11 00:59  努力成长静待花开  阅读(1713)  评论(0编辑  收藏  举报

实现效果:

  

知识运用:

  File类的OpenWrite方法      //实现打开现有文件以进行写入

  public static FileStream OpenWrite (string path)

  Encoding抽象类的GetBytes方法  //将指定的字符串中的所有字符编码为一个字节序列

  public virtual byte[] GetBytes (string s)

实现代码:

        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("请设置文件");
                return;
            }
            try
            {
                FileStream fs = File.OpenWrite(textBox1.Text);
                byte[] b = Encoding.UTF8.GetBytes(textBox2.Text);
                fs.Write(b,0,b.Length);
                fs.Close();
                MessageBox.Show("写入成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }