C#--之文件操作

时间:2022-04-16 08:23:55

1、从文本文件中读取一行文本

StreamReader sr = new StreamReader("C:\\1.txt");
string readline = sr.ReadLine();//从文件中读取一行
while(readline = sr.ReadLine()!=null)
{
Console.WriteLine(readline);//按行来逐行读取
}

2、向文本文件中写入数据

按行写,每次写入一行:

StreamWriter  sw = new StreamWriter("C:\\1.txt",true);//逐行写入,在写入一行后会自动换行,如果文件中有数据的话,会以追加的方式写入,不会破坏原来的文件
StreamWriter sw = new StreamWriter("C:\\1.txt",false);//逐行写入,也是会自动换行,如果原来文件中有数据的话,会把原来的数据擦除,默认的方式是这种
sw.WriteLine("这是写入的一行数据,不用加\\r和\\n,就会自动换行了");
sw.close();//关闭操作