将textBox读入新的文本文档中并保存
//private string filepath = "";
if (filepath.Length == 0)
{
filepath = saveFileDialog1.FileName;
//获取当前要保存的文件路径
}
StreamWriter sTmp = new StreamWriter(filepath);
sTmp.Write(textBox1.Text); //将字符串写入流
sTmp.Flush(); //将缓冲区数据写入流,并清理所有缓冲区
sTmp.Close(); //关闭StreamWriter对象
MessageBox.Show("保存成功!");
从一个文本文档中读取内容到textBox中
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
dirty = false;
//这里要注意根据所打开的文本文档编码格式不同,Encodeing属性要使用不同的属性,常用有ASCII,UTF-8,Unicode
StreamReader sTmp = new StreamReader(openFileDialog1.FileName,System.Text.Encoding.Default);
filepath = openFileDialog1.FileName;
richTextBox1.Text = "";
richTextBox1.Text = sTmp.ReadToEnd();
}
打开文件乱码解决方法
StreamReader对象的参数System.TextEncoding.Default/ASCII/UTF-8/Unicode尝试一遍即可正确读取。