1:当点击Button1时选择文件,当点击Button2时文件另存为
private void button1_Click(object sender, EventArgs e) { openFileDialog1.Filter = "*.txt(文本文件)|*.txt";//设置打开文件格式 if(openFileDialog1.ShowDialog()==DialogResult.OK)//判断是否选择文件 { //实例化读取数据流 StreamReader SReader = new StreamReader(openFileDialog1.FileName,Encoding.Default); richTextBox1.Text = SReader.ReadToEnd();//显示打开文件的内容 SReader.Close(); //关闭读取数据流 } } private void button2_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "*.txt(文本文件)|*.txt";//设置打开文件格式 if (saveFileDialog1.ShowDialog()==DialogResult.OK)//判断是否输入了另存为文件名 { //实例化写入数据流 StreamWriter SWrite = new StreamWriter(saveFileDialog1.FileName, true); SWrite.Write(richTextBox1.Text);//向文件中写入数据 SWrite.Close(); //关闭写入数据流 } }
原文:https://www.cnblogs.com/clhxxlcj/p/10936723.html