Form1.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. namespace WindowsFormsIOFileStream
  12. {
  13. public partial class Form1 : Form
  14. {
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. }
  19. //写入
  20. private void button1_Click(object sender, EventArgs e)
  21. {
  22. //判断要写入的内容不能为空
  23. if (textBox1.Text == string.Empty)
  24. {
  25. MessageBox.Show("要写入的文件内容不能为空");
  26. }
  27. else
  28. {
  29. //设置保存文件的格式
  30. saveFileDialog1.Filter = "文本文件(*.txt)|*.txt";
  31. if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  32. {
  33. //使用“另存为”对话框中输入的文件名实例化StreamWriter对象
  34. StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, true);
  35. //向创建的文件中写入内容
  36. sw.WriteLine(textBox1.Text);
  37. //关闭当前文件写入流
  38. sw.Close();
  39. textBox1.Text = string.Empty;
  40. }
  41. }
  42. }
  43. //读取
  44. private void button2_Click(object sender, EventArgs e)
  45. {
  46. //设置打开文件的格式
  47. openFileDialog1.Filter = "文本文件(*.txt)|*.txt";
  48. if (openFileDialog1.ShowDialog() == DialogResult.OK)
  49. {
  50. textBox1.Text = string.Empty;
  51. //使用“打开”对话框中选择的文件实例化StreamReader对象
  52. StreamReader sr = new StreamReader(openFileDialog1.FileName);
  53. //调用ReadToEnd方法读取选中文件的全部内容
  54. textBox1.Text = sr.ReadToEnd();
  55. //关闭当前文件读取流
  56. sr.Close();
  57. }
  58. }
  59. }
  60. }