c#文件流操作

2024-04-23 18:21:37 浏览数 (3)

一个文件流操作简单的demo

这里写图片描述这里写图片描述
代码语言:javascript复制
 //写入文件
        private void button1_Click(object sender, EventArgs e)
        {

            //(创建文件)创建文件流
            FileStream fs = new FileStream("F:\myfile\myfile.txt", FileMode.Create);
            //创建写入流
            StreamWriter sw = new StreamWriter(fs);
            //以流的方式写入数据
            sw.Write(this.textBox1.Text.Trim());
            //关闭写入流
            sw.Close();
            //关闭文件流
            fs.Close();

        }
        //读取文件
        private void button2_Click(object sender, EventArgs e)
        {
            //(读取文件)创建文件流
            FileStream fs = new FileStream("F:\myfile\myfile.txt",FileMode.Open);
            //创建读取流
            StreamReader sr = new StreamReader(fs);
            //以流的方式读取数据
            this.textBox1.Text = sr.ReadToEnd();
            //关闭读取器
            sr.Close();
            //关闭文件流
            fs.Close();

        }
        //追加文件内容
        private void button3_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream("F:\myfile\myfile.txt", FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(DateTime.Now.ToString() "[文件操作正常!]");
            sw.Close();
            fs.Close();
        }
        //删除文件
        private void button4_Click(object sender, EventArgs e)
        {
            File.Delete("F:\myfile\myfile.txt");
        }
        //复制文件
        private void button5_Click(object sender, EventArgs e)
        {
            if (File.Exists(this.textBox3.Text.Trim()))
            {
                File.Delete(this.textBox3.Text.Trim());
            }
            File.Copy(this.textBox2.Text.Trim(), this.textBox3.Text.Trim());
        }

        //移动文件
        private void button6_Click(object sender, EventArgs e)
        {
            if (File.Exists(this.textBox3.Text.Trim()))
            {
                File.Delete(this.textBox3.Text.Trim());
            }
            if (File.Exists(this.textBox2.Text.Trim()))
            {
                File.Move(this.textBox2.Text.Trim(), this.textBox3.Text.Trim());
            }
            else
            {
                MessageBox.Show("文件不存在!");
            }
        }

0 人点赞