private void btnSave_Click(object sender, EventArgs e)//保存
{
SaveFileDialog SaveAddr = new SaveFileDialog();
SaveAddr.Filter = "文本文件.txt|*.txt";//设置Filter属性,及在对话框中现实的文件类型
SaveAddr.DefaultExt = "*.txt";//默认文件扩展名
SaveAddr.ShowDialog();//弹出对话框
string result = txtWrite.Text.Trim(); //输入文本
StreamWriter sw = File.AppendText(SaveAddr.FileName); //保存到指定路径
sw.Write(result);
sw.Flush();
sw.Close();
}
private void btnRead_Click(object sender, EventArgs e)//读取
{
OpenFileDialog ReadAddr = new OpenFileDialog();
ReadAddr.Filter = "文本文件.txt|*.txt";
ReadAddr.ShowDialog();
if (ReadAddr.FileName == "") return;//如果地址为空,直接退出
if (!File.Exists(ReadAddr.FileName))//验证所选文件是否存在
{
MessageBox.Show("文件不存在");
return;
}
StreamReader sr = new StreamReader(ReadAddr.FileName, Encoding.Default);
string content;
while ((content = sr.ReadLine()) != null)
{
txtWrite.Text += content.ToString();
}
}
程序控件: