1、文件的讀與寫:
在c#中,,讀寫文件的操作流程:
其中,,使用FileStream的時候,需要引用命名空間:
using System.IO;
2,、文件流(FileStream):
step ①:創(chuàng)建文件流: 在讀寫文件的過程中,,首先要開啟文件流; 在c#中,,使用FileStream 類創(chuàng)建文件流。
FileStream(String FilePath , FileMode)
在這里,,傳入了兩個參數(shù),,F(xiàn)ilePath 是對應(yīng)文件讀寫的path, FileMode 是對要進行讀寫文件的打開方式,。 其中,,參數(shù)FileMode是枚舉(enum)類型,F(xiàn)ileMode有如下成員:
step ②:關(guān)閉文件流: 使用完畢讀寫器,記得要關(guān)閉讀寫器,,這里用到了FileStream 對象中的.close()方法,。
3、文件讀寫器:
1)StreamWriter寫入器: 首先要創(chuàng)建好文件流,,然后再創(chuàng)建閱讀器或者寫入器(根據(jù)需求),; 在這里,寫入器就用到了StreamWriter類,,用來將數(shù)據(jù)寫入文件流中,, 打開文件流后就可以new一個StreamWriter的對象。 StreamWriter可以調(diào)用的方法如下:
StreamWriter.Write();//寫入流,。 StreamWriter.WriteLine();//寫入一行數(shù)據(jù)后自動換行,。 StreamWriter.Close();//關(guān)閉寫入器 2)StreamReader讀取器:
同理,使用前要創(chuàng)建好文件流,,然后創(chuàng)建讀取器(StreamReader),; 讀取器用到了StreamReader類,調(diào)用方法如下:
StreamReader.ReadLine();//讀取文件流中的一行數(shù)據(jù),,返回字符串,。 StreamReader.ReadToEnd();//從當(dāng)前位置讀取到結(jié)束,返回字符串,。 StreamReader.Close();//關(guān)閉讀取器,。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace MyPerson { public partial class FileStreamRW : Form { public FileStreamRW() { InitializeComponent(); } private void btnRead_Click(object sender, EventArgs e) { string path, content; path = txtPath.Text; content = txtContent.Text; if (String.IsNullOrEmpty(path) == true) { MessageBox.Show("路徑不能為空"); return; } try { //創(chuàng)建文件流 FileStream myFs = new FileStream(path, FileMode.Open); //創(chuàng)建讀取器 StreamReader mySr = new StreamReader(myFs); //讀取文件所有的內(nèi)容 content = mySr.ReadToEnd(); //將讀取到的內(nèi)容賦給txtCotent控件。 txtContent.Text = content; //關(guān)閉讀取器和文件流,。 mySr.Close(); myFs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } private void btnWrite_Click(object sender, EventArgs e) { string path, content; path = txtPath.Text; content = txtContent.Text; if (String.IsNullOrEmpty(path) == true) { MessageBox.Show("文件路徑不能為空"); return; } try { //創(chuàng)建文件流 FileStream myFs = new FileStream(path, FileMode.Create); //創(chuàng)建寫入器 StreamWriter mySw = new StreamWriter(myFs); //將敲擊的內(nèi)容寫入文件中,。 mySw.Write(content); MessageBox.Show("寫入成功!"); //關(guān)閉寫入器和文件流,。 mySw.Close(); myFs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } } }
4,、文件和目錄操作:
1)File類和Directory類: ①:File類的方法:
②:Directory類的方法:
2)靜態(tài)類與非靜態(tài)類: File類和Directory類在使用方法的時候不需要實例化,,直接.方法名() 就可以使用,。 靜態(tài)類和非靜態(tài)類的區(qū)別:
|
|