c#语言中读取txt文件,简单的c#文本文件读写-.NET教程,C#语言
system.io命名空間中的類為托管應(yīng)用程序提供文件以及其他形式的輸入輸出。托管i/o的基本構(gòu)件是流,而流是字節(jié)導(dǎo)向的數(shù)據(jù)的抽象表示。流通過(guò)system.io.stream類表示.
system.io.filestream允許將文件作為流訪問(wèn);
system.io.memorystream允許將內(nèi)存塊作為流進(jìn)行訪問(wèn);…………
托管和非托管的應(yīng)用程序最常使用的io形式是文件io。托管應(yīng)用程序讀寫(xiě)文件的一般步驟如下
1、用filestream對(duì)象打開(kāi)文件
2、進(jìn)行二進(jìn)制讀寫(xiě)操作,在filestream對(duì)象周圍包裝binaryreader和binarywriter的實(shí)例,并調(diào)用binaryreader和binarywriter方法執(zhí)行輸入輸出。
3、要讀寫(xiě)文本,在filestream對(duì)象的周圍包裝一個(gè)streamreader和streamwriter,然后使用streamreader和streamwriter方法完成輸入輸出。
4、關(guān)閉filestream對(duì)象。
下面是一個(gè)簡(jiǎn)單的文本文件讀操作
using system;
using system.io;
class filetest
{
static void main(string [] args)
{
string filename=”testfile.txt”;
//打開(kāi)文件并顯示其內(nèi)容
streamreader reader=null;
try
{
reader=new streamreader(filename);
for(string line=reader.readline();line!=null;line=reader.readline())
console.writeline(line);
}
catch(ioexception e)
{
console.writeline(e.message);
}
finally
{
if(reader!=null)
reader.close();
}
}
}
/**
* fcl是一個(gè)非常豐富的類庫(kù),所以還有許多打開(kāi)文件并進(jìn)行讀取的方法,比如
* 1.用file.open創(chuàng)建一個(gè)filestream,并圍繞它包裝一個(gè)streamreader
* filestream stream=file.open(filename,filemode.open,fileaccess.read);
* streamreader reader=new streamreaderaa(stream);
* 2.使用file.opentext,在一步內(nèi)創(chuàng)建一個(gè)filestream和一個(gè)streamreader
* streamreader reader=file.opentext(filename);
* 當(dāng)然,還有其他的方法
* 若要對(duì)文本進(jìn)行寫(xiě)入操作,可以使用streamwriter
*/
其中的異常處理是為了防止意外的事情發(fā)生,如傳遞給streamreader的構(gòu)造函數(shù)的文件名非法,或者在執(zhí)行raeder.close();前匡架引發(fā)異常等。
總結(jié)
以上是生活随笔為你收集整理的c#语言中读取txt文件,简单的c#文本文件读写-.NET教程,C#语言的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2133内存时序设置大揭秘:性能提升秘籍
- 下一篇: 天价内存条:性能超群还是画蛇添足?