C#中写入文件和读取文件有很多种方式,现分享两种读写文件的方式
1.System.IO.File的方式
1.写入:
using System.IO;
string path = @"D:\学习\File.txt";
File.AppendAllText(path,"这是写入字符串"+"\r\n",Encoding.UTF8);
执行上面代码后,会在文件中以UTF8的格式写入字符串,写入后会自动关闭文件,当然,只能写入可读写为文件。
2.读取:
using System.IO;
string path = @"D:\学习\File.txt";
File.AppendAllText(path, "这是写入字符串" + "\r\n", Encoding.UTF8);
string[] contents = File.ReadAllLines(path, Encoding.UTF8);
string content =File.ReadAllText(path, Encoding.UTF8);
其中contents是一个数组,以文件中顺序为准,不会乱
content是一个字符串,以"\r\n"分割,也是以文件中的顺序为准,不会乱。
两种方式可以任选其一,写入完文件后都会关闭文件,不用写try,catch代码块
2.System.IO.StreamReader/System.IO.StreamWriter
1.写入:
using System.IO;
string path = @"D:\学习\File.txt";
StreamWriter sw = new StreamWriter(path,true,Encoding.UTF8,4096);
sw.Write("这是写入字符串" + "\r\n");
sw.Close();
2.读取:
using System.IO;
string path = @"D:\学习\File.txt";
StreamReader st = new StreamReader(path);
string content = st.ReadToEnd();
st.Close();