c# 读取txt文档和写入文档的方法

StreamReader sr = new StreamReader(path); //path是要读取的文件的完整路径

String str_read = sr.ReadToEnd();  //从开始到末尾读取文件的所有内容,str_read 存放的就是读取到的文本
sr.Close();  //读完文件记得关闭流
 
如果要一条一条读

while ((content = sr.ReadLine()) != null)//按行输出
{
f+=content;
}

写入文档方法

//FileMode.Append为不覆盖文件效果.create为覆盖
FileStream fs = new FileStream(path, mode: FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
//开始写入

sw.Write(“xxxxx”);
//清空缓冲区
sw.Flush();
//关闭
sw.Close();
fs.Close();

猜你喜欢

转载自www.cnblogs.com/Aspfengge/p/9376099.html