C#读写文本文件小结

 

除了创建、复制、移动和删除外,对文本文件最常用的操作就是进行读写,C#提供了非常多的方法来对文本文件进行读写,今天我们做个小结:

一、写入文件

1.File类的静态方法WriteAllText(改写方式)

 程序代码
File.WriteAllText(Server.MapPath("a.txt"), "http://www.mzwu.com//r/nhttp://www.hao123.com//r/nhttp://www.163.com/");

2.File类的静态方法WriteAllLines(改写方式)

 程序代码
File.WriteAllLines(Server.MapPath("a.txt"), new string[] { "http://www.mzwu.com/", "http://www.hao123.com/", "http://www.163.com/" });

3.File类的静态方法AppendAllText(追加方式)

 程序代码
File.AppendAllText(Server.MapPath("a.txt"), "http://www.mzwu.com//r/nhttp://www.hao123.com//r/n");
File.AppendAllText(Server.MapPath("a.txt"), "http://www.163.com/");

4.StreamWriter对象的Write方法和WriteLine方法(true追加,false改写)

 程序代码
StreamWriter sw = new StreamWriter(Server.MapPath("a.txt"), false);
sw.Write("http://www.mzwu.com//r/n");
sw.WriteLine("http://www.mzwu.com/");
sw.WriteLine("http://www.163.com/");
sw.Close();

说明:当文件不存在时,以上方法都将创建一个新文件!

二、读取文件

1.File类的静态方法ReadAllText

 程序代码
File.ReadAllText(Server.MapPath("a.txt"))

2.File类的静态方法ReadAllLines

 程序代码
string[] content = File.ReadAllLines(Server.MapPath("a.txt"));
for (int i = 0; i < content.Length; i++)
{
    Response.Write(content[i] + "<br/>");
}

3.StreamReader对象的ReadToEnd方法

 程序代码
StreamReader sr = new StreamReader(Server.MapPath("a.txt"));
Response.Write(sr.ReadToEnd());
sr.Close();

4.StreamReader对象的ReadLine方法

 程序代码
StreamReader sr = new StreamReader(Server.MapPath("a.txt"));
while (!sr.EndOfStream)
{
    Response.Write(sr.ReadLine() + "<br/>");
}
sr.Close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值