文本操作

文本操作:

        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编码。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值