文本操作:
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.youkuaiyun.com/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编码。