C#操作文本文件演練實(shí)例淺析
作者:ltt1987
C#操作文本文件演練實(shí)例主要向你介紹了一個(gè)在C#操作文本文件學(xué)習(xí)中的一個(gè)總結(jié)體會(huì)的應(yīng)用,希望對(duì)你學(xué)習(xí)C#操作文本文件有所幫助。
C#操作文本文件演練實(shí)例淺析
- /*
- * 本講解用C#如何處理文本文件,內(nèi)容重點(diǎn)是如何建立一個(gè)文件讀取文本文件內(nèi)容
- *
- * 如何改把揚(yáng)輝三角形輸入文件內(nèi)容
- *
- * 下面我介紹一個(gè)幾個(gè)使用的類(lèi):
- *
- *1.FileInfo類(lèi):這個(gè)類(lèi)提供典型的操作,
- 比如:復(fù)制、移動(dòng)、重命名、創(chuàng)建、打開(kāi)、刪除和追加
- 到文件。如導(dǎo)入現(xiàn)成的文本文件,也可以創(chuàng)建一個(gè)不存在的文件
- string path = @"c:\temp\MyTest.txt";
- FileInfo fi = new FileInfo(path);
- 這里的@將一個(gè)字符變成一個(gè)逐字字符串
- *
- *2.StreamReader類(lèi)和StreamWriter類(lèi):
- 這兩個(gè)類(lèi)是為了處理字符流特別設(shè)計(jì)的,這些流只能用于文本
- 文件,無(wú)法用于二進(jìn)制文件
- * */
- using System;
- using System.IO;//因?yàn)槭俏谋疚募僮?,所以要是用到IO這個(gè)包
- namespace yanghuisanjiao
- {
- /// ﹤summary﹥
- /// Class1 的摘要說(shuō)明。
- /// ﹤/summary﹥
- class Program
- {
- /// ﹤summary﹥
- /// 應(yīng)用程序的主入口點(diǎn),C#操作文本文件
- /// ﹤/summary﹥
- [STAThread]
- static void Main(string[] args)
- {
- StreamWriter sw;
- StreamReader inStr = null;
- string textLine = null;
- int[,] a = new int[10,10];
- a[0,0] = 1;//初始化數(shù)組
- for(int i = 1;i ﹤ 10;i++)
- {
- a[i,0] = 1;
- a[i,i] = 1;
- for(int j = 1;j ﹤ i;j++)
- {
- a[i,j] = a[i-1,j-1] + a[i-1,j];
- }
- }
- try
- {
- sw = File.CreateText("yanghui.txt");
- //C#操作文本文件
- //txt文件會(huì)創(chuàng)建到跟目錄下的BIN→Debug下
- }
- catch
- {
- Console.WriteLine("不能創(chuàng)建文件!");
- return;
- }
- for(int i = 0;i ﹤ 10;i++)
- {
- for(int j = 0;j ﹤= i;j++)
- {
- sw.Write("{0} ",a[i,j]);
- }
- sw.WriteLine();//換行
- }
- sw.Close();
- //C#操作文本文件
- //讀取文件yanghui.txt(從Debug文件夾下讀取)
- FileInfo textFile = new FileInfo(@"yanghui.txt");
- inStr = textFile.OpenText();
- Console.WriteLine("\n讀取文本文件內(nèi)容如下: \n");
- textLine = inStr.ReadLine();
- while(textLine != null)
- {
- Console.WriteLine(textLine);
- textLine = inStr.ReadLine();
- }
- inStr.Close();
- }
- }
- }
C#操作文本文件實(shí)例的應(yīng)用就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#操作文本文件有所幫助。
【編輯推薦】
責(zé)任編輯:仲衡
來(lái)源:
博客園