【C#】利用富文本框打开,保存text文件【源代码】
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = "F:\\"; //设置初始目录
open.Filter = "文本文件(*.txt)|*.*|(*.htm)|*.htm"; //打开htm类型文件或text文件
open.RestoreDirectory = true; //设置对话框在关闭前还原当前目录
open.FilterIndex = 1;
if (open.ShowDialog() == DialogResult.OK)
{
string str = open.FileName;
StreamReader sr = File.OpenText(str);
string s;
while ((s = sr.ReadLine()) != null)
this.richTextBox1.Text += s;
sr.Close();
}
}
private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = "C:\\";
save.Filter = "(*.txt)|*.*|(*.cs)|*.cs"; //打开cs文件或text文件
save.RestoreDirectory = true;
save.FilterIndex = 1;
if (save.ShowDialog() == DialogResult.OK)
{
string str = save.FileName;
//向指定的文件中追加内容,如果文件不存在,则创建文件
StreamWriter sw = File.AppendText(str);
sw.Write(this.richTextBox1.Text);
sw.Flush();
sw.Close();
}
}