C# 之文件读与写(File/StreamReader/StreamWriter)

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值