zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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

文件方法 进行 打开 写入 现有
2023-09-14 08:58:58 时间

实现效果:

  

知识运用:

  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);
            }
        }