读取
//直接读取出字符串
string text = System.IO.File.ReadAllText(@"D:\web\test.txt");
Console.WriteLine(text);
//按行读取为字符串数组
string[] lines = System.IO.File.ReadAllLines(@"D:\web\test.txt");
foreach (string line in lines)
{
Console.WriteLine(line);
}
//从头到尾以流的方式读出文本文件
//该方法会一行一行读出文本
using (System.IO.StreamReader sr = new System.IO.StreamReader(@"D:\web\test.txt"))
{
string str;
while ((str = sr.ReadLine()) != null)
{
Console.WriteLine(str);
}
}
Console.Read();
写入
//该方法写入字符数组换行显示
string[] lines = { "一", "二", "三","四" };
System.IO.File.WriteAllLines(@"D:\web\test.txt", lines, Encoding.UTF8);
string strTest = "我是一个字符串";
System.IO.File.WriteAllText(@"D:\web\test1.txt", strTest, Encoding.UTF8);
//StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾 默认为false
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\web\test.txt",true))
{
foreach (string line in lines)
{
if (!line.Contains("second"))
{
file.Write(line);//直接追加文件末尾,不换行
file.WriteLine(line);// 直接追加文件末尾,换行
}
}
}