当前位置:   article > 正文

C#中txt文件的读取和写入

C#中txt文件的读取和写入

C# winform的程序内用openfiledialog来打开对话框选择文件, 用savefiledialog来打开对话框显示要存储的文件名和文件路径

程序代码如下:

  1. private void button2_Click(object sender, EventArgs e)
  2. {
  3. OpenFileDialog ofldg = new OpenFileDialog();
  4. ofldg.Title = "选择需要打开的文件";
  5. ofldg.Filter = "Txt(*.txt)|*.txt";
  6. ofldg.InitialDirectory = @"D:\";
  7. if (ofldg.ShowDialog() == DialogResult.OK)
  8. {
  9. string filename = ofldg.FileName;
  10. textBox2.Text = filename;
  11. try
  12. {
  13. // 创建一个 StreamReader 的实例来读取文件
  14. // using 语句也能关闭 StreamReader
  15. StreamReader streamReader = new StreamReader(filename);
  16. //判断文件中是否有字符
  17. while (streamReader.Peek() != -1)
  18. {
  19. //读取文件中的一行字符
  20. string str = streamReader.ReadToEnd();
  21. textBox1.Text = str ;
  22. }
  23. streamReader.Close();
  24. }
  25. catch (Exception ex)
  26. {
  27. MessageBox.Show(ex.Message);
  28. }
  29. }
  30. }
  31. private void button1_Click(object sender, EventArgs e)
  32. {
  33. SaveFileDialog sflg = new SaveFileDialog();
  34. sflg.Filter = "Txt(*.txt)|*.txt";
  35. if(sflg.ShowDialog() == DialogResult.OK)
  36. {
  37. textBox2.Text = sflg.FileName;
  38. StreamWriter swriter = new StreamWriter(sflg.FileName, true);
  39. swriter.Write(textBox1.Text);
  40. }
  41. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/140696?site
推荐阅读
相关标签
  

闽ICP备14008679号