通过流的方式读取文件内容,和为txt文本进行写入
需要引用System.IO
//读取:
public static void Read(string filePath)
{
//创建读取流,并指定路径文件
StreamReader sr = new StreamReader(filePath);
//读取文件的所有字符
string str = sr.ReadToEnd();
Console.WriteLine(str.ToString());
//关闭流
sr.Close();
}
//写入:
public static void Wirte(string filePath)
{
//检查是否存在该文件,若存在则删除
if (File.Exists(filePath)) File.Delete(filePath);
//根据路径创建流文件
FileStream fs = new FileStream(filePath, System.IO.FileMode.Create);
//创建一个写入流,写入文件为fs
StreamWriter sw = new StreamWriter(fs);
string str = "要写入的string字符串";
sw.Write(str);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
//关闭文件
fs.Close();
}