欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-13 23:47:54
StreamReader sr = new StreamReader(path); //path是要读取的文件的完整路径 String str_read = sr.ReadToEnd(); //从开始到末尾读取文件的所有内容,str_read 存放的就是读取到的文本 sr.Close(); //读完 ......

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();