文本操作

文本操作:

        1、一次讀取一行文本,代碼如下:

int counter = 0;string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{ 
Console.WriteLine (line); 
counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();


       另:一次讀取一行文本的方式可能有多種,另外一種方式可以通過.ReadToEnd()整個讀取文本信息,然後再以"\r\n "回車換行符string.Split()到數組中去。

               但因涉及到程序效率問題,所以基本用上面那種方式進行文本處理。

               有興趣的同學可以參看下:http://topic.csdn.net/t/20060614/15/4821206.html   這個討論。


        2、向文本寫入信息

       

// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);

file.Close();
            如果要向現有文本文件中追加內容,則要把StreamWriter的布爾參數設置爲true:

System.IO.StreamWriter file =
   new System.IO.StreamWriter("c:\\test.txt", true);


備註:StreamReader和SteamWriter類,默認都使用UTF-8編碼。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章