欢迎来到山村网

C#读写文本文件的方法

2019-03-02 13:34:41浏览:512 来源:山村网   
核心摘要:  本文实例讲述了C#读写文本文件的方法。分享给大家供大家参考。具体分析如下:  System.IO命名空间中的类为托管应用程序提

  本文实例讲述了C#读写文本文件的方法。分享给大家供大家参考。具体分析如下:

  System.IO命名空间中的类为托管应用程序提供文件以及其他形式的输入输出。托管i/o的基本构件是流,而流是字节导向的数据的抽象表示。流通过System.IO.Stream类表示.

  System.IO.FileStream允许将文件作为流访问;

  System.IO.MemoryStream允许将内存块作为流进行访问

  以下为读写文件的示例

  先引用命名空间

  using System.IO;

  以下是源代码

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 namespace 文本文件打开测试 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btn_Read_Click(object sender, EventArgs e) { //异常检测开始 try { FileStream fs = new FileStream(@tB_PachFileName.Text , FileMode.Open, FileAccess.Read);//读取文件设定 StreamReader m_streamReader = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));//设定读写的编码 //使用StreamReader类来读取文件 m_streamReader.baseStream.Seek(0, SeekOrigin.Begin); // 从数据流中读取每一行,直到文件的最后一行,并在rTB_Display.Text中显示出内容 this.rTB_Display.Text = ""; string strLine = m_streamReader.ReadLine(); while (strLine != null) { this.rTB_Display.Text += strLine + "n"; strLine = m_streamReader.ReadLine(); } //关闭此StreamReader对象 m_streamReader.Close(); } catch { //抛出异常 MessageBox.Show("指定文件不存在"); return; } //异常检测结束 } private void btn_Replace_Click(object sender, EventArgs e) { //判断替换开始 if (tB_Replace.Text == ""&&tB_Replace_2.Text=="") { MessageBox.Show("想替换的字符都没有就换啊,你太有才了"); } else { if (rTB_Display.Text == "") { MessageBox.Show("文件内容为空无法进行替换,请检查文件"); } else { string str = rTB_Display.Text.ToString(); rTB_Display.Text = str.Replace(@tB_Replace.Text ,@tB_Replace_2.Text);//替换 } } //结束 } private void btn_Save_Click(object sender, EventArgs e) { //异常检测开始 try { //创建一个文件流,用以写入或者创建一个StreamWriter FileStream fs = new FileStream(@tB_Save.Text, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter(fs); m_streamWriter.Flush(); // 使用StreamWriter来往文件中写入内容 m_streamWriter.baseStream.Seek(0, SeekOrigin.Begin); // 把richTextBox1中的内容写入文件 m_streamWriter.Write(rTB_Display.Text); //关闭此文件 m_streamWriter.Flush(); m_streamWriter.Close(); } catch { //抛出异常 MessageBox.Show("写入文件失败,请检查路径 文件名与权限是否符合"); } //异常检测结束 } } }

  希望本文所述对大家的C#程序设计有所帮助。

(责任编辑:豆豆)
下一篇:

C#创建IIS虚拟目录的方法

上一篇:

C#实现rar压缩与解压缩文件的方法

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com