C#操作文本文件演練實例淺析
作者:ltt1987
C#操作文本文件演練實例主要向你介紹了一個在C#操作文本文件學習中的一個總結體會的應用,希望對你學習C#操作文本文件有所幫助。
C#操作文本文件演練實例淺析
- /*
- * 本講解用C#如何處理文本文件,內容重點是如何建立一個文件讀取文本文件內容
- *
- * 如何改把揚輝三角形輸入文件內容
- *
- * 下面我介紹一個幾個使用的類:
- *
- *1.FileInfo類:這個類提供典型的操作,
- 比如:復制、移動、重命名、創建、打開、刪除和追加
- 到文件。如導入現成的文本文件,也可以創建一個不存在的文件
- string path = @"c:\temp\MyTest.txt";
- FileInfo fi = new FileInfo(path);
- 這里的@將一個字符變成一個逐字字符串
- *
- *2.StreamReader類和StreamWriter類:
- 這兩個類是為了處理字符流特別設計的,這些流只能用于文本
- 文件,無法用于二進制文件
- * */
- using System;
- using System.IO;//因為是文本文件操作,所以要是用到IO這個包
- namespace yanghuisanjiao
- {
- /// ﹤summary﹥
- /// Class1 的摘要說明。
- /// ﹤/summary﹥
- class Program
- {
- /// ﹤summary﹥
- /// 應用程序的主入口點,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;//初始化數組
- 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文件會創建到跟目錄下的BIN→Debug下
- }
- catch
- {
- Console.WriteLine("不能創建文件!");
- 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");
- textLine = inStr.ReadLine();
- while(textLine != null)
- {
- Console.WriteLine(textLine);
- textLine = inStr.ReadLine();
- }
- inStr.Close();
- }
- }
- }
C#操作文本文件實例的應用就向你介紹到這里,希望對你了解和學習C#操作文本文件有所幫助。
【編輯推薦】
責任編輯:仲衡
來源:
博客園