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 | 查看次数: 5505
发表评论
登录后再发表评论!