C#讀寫文本文件的方法
本文實(shí)例講述了C#讀寫文本文件的方法。分享給大家供大家參考。具體分析如下:
System.IO命名空間中的類為托管應(yīng)用程序提供文件以及其他形式的輸入輸出。托管i/o的基本構(gòu)件是流,而流是字節(jié)導(dǎo)向的數(shù)據(jù)的抽象表示。流通過System.IO.Stream類表示.
System.IO.FileStream允許將文件作為流訪問;
System.IO.MemoryStream允許將內(nèi)存塊作為流進(jìn)行訪問
以下為讀寫文件的示例
先引用命名空間
using System.IO;
以下是源代碼
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);//讀取文件設(shè)定 StreamReader m_streamReader = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));//設(shè)定讀寫的編碼 //使用StreamReader類來讀取文件 m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin); // 從數(shù)據(jù)流中讀取每一行,直到文件的最后一行,并在rTB_Display.Text中顯示出內(nèi)容 this.rTB_Display.Text = ""; string strLine = m_streamReader.ReadLine(); while (strLine != null) { this.rTB_Display.Text += strLine + "\n"; strLine = m_streamReader.ReadLine(); } //關(guān)閉此StreamReader對象 m_streamReader.Close(); } catch { //拋出異常 MessageBox.Show("指定文件不存在"); return; } //異常檢測結(jié)束 } 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("文件內(nèi)容為空無法進(jìn)行替換,請檢查文件"); } else { string str = rTB_Display.Text.ToString(); rTB_Display.Text = str.Replace(@tB_Replace.Text ,@tB_Replace_2.Text);//替換 } } //結(jié)束 } private void btn_Save_Click(object sender, EventArgs e) { //異常檢測開始 try { //創(chuàng)建一個文件流,用以寫入或者創(chuàng)建一個StreamWriter FileStream fs = new FileStream(@tB_Save.Text, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter(fs); m_streamWriter.Flush(); // 使用StreamWriter來往文件中寫入內(nèi)容 m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin); // 把richTextBox1中的內(nèi)容寫入文件 m_streamWriter.Write(rTB_Display.Text); //關(guān)閉此文件 m_streamWriter.Flush(); m_streamWriter.Close(); } catch { //拋出異常 MessageBox.Show("寫入文件失敗,請檢查路徑 文件名與權(quán)限是否符合"); } //異常檢測結(jié)束 } } }
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C# WinForm捕獲全局變量異常 SamWang解決方法
本文將介紹C# WinForm捕獲全局變量異常 SamWang解決方法,需要的朋友可以參考2012-11-11c#實(shí)現(xiàn)16進(jìn)制和字符串之間轉(zhuǎn)換的代碼
#中十六進(jìn)制字符串的轉(zhuǎn)換函數(shù)2007-05-05Entity?Framework代碼優(yōu)先(Code?First)模式
這篇文章介紹了Entity?Framework代碼優(yōu)先(Code?First)模式,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06C# Oracle數(shù)據(jù)庫操作類實(shí)例詳解
這篇文章主要介紹了C# Oracle數(shù)據(jù)庫操作類實(shí)例,進(jìn)行數(shù)據(jù)庫操作時很有實(shí)用價值,需要的朋友可以參考下2014-07-07