/// <summary> /// 打开文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnFile_Click(object sender, EventArgs e) { using (OpenFileDialog openFile = new OpenFileDialog()) {
openFile.Filter = "文本文档|*.txt|All files (*.*)|*.*"; if (openFile.ShowDialog() != DialogResult.OK) { return; } using (FileStream fileStream = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fileStream)) { while (!sr.EndOfStream) { string line = sr.ReadLine(); this.txtContent.Text = line; } } } } } /// <summary> /// 保存文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSaveFile_Click(object sender, EventArgs e) { using (SaveFileDialog saveFile = new SaveFileDialog()) {
saveFile.Filter = "文本文档|*.txt|All files (*.*)|*.*"; if (saveFile.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } using (FileStream fs = new FileStream(saveFile.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { //using (StreamWriter sw = new StreamWriter(fs)) //{ // sw.Write(txtContent.Text); // sw.Flush(); //} string str= txtContent.Text; byte[] result = Encoding.Default.GetBytes(str); fs.Write(result, 0, result.Length); fs.Flush(); } } }