0
点赞
收藏
分享

微信扫一扫

C#中使用StreamReader实现文本文件的读取与写入


场景

实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。

实现

文本文件读取

新建命令窗口程序。

在main方法中:

//使用StramReader来读取一个文本文件
using (StreamReader sr = new StreamReader(@"C:\Users\Administrator\Desktop\badao.txt",Encoding.Default))
{
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
Console.ReadKey();

在上面的代码中读取了指定文件路径和指定了编码格式的文本文件。

效果

C#中使用StreamReader实现文本文件的读取与写入_C#

 

文本文件写入

//使用StreamWriter来写入一个文本文件
using (StreamWriter sw = new StreamWriter(@"C:\Users\Administrator\Desktop\new.txt"))
{
sw.Write("关注公众号:霸道的程序猿,获取编程相关电子书、教程推送与免费下载。大量编程视频教程:https://space.bilibili.com/164396311");
}
Console.WriteLine("写入成功");
Console.ReadKey();

效果

C#中使用StreamReader实现文本文件的读取与写入_文本文件_02

大量编程视频教程:​​https://space.bilibili.com/164396311​​

 

举报

相关推荐

0 条评论