当前位置:网站首页>基于C#实现文本读取的7种方式
基于C#实现文本读取的7种方式
2022-04-21 12:11:00 【华为云】
@TOC
博主介绍
作者主页:苏州程序大白
作者简介:CSDN人工智能域优质创作者,苏州市凯捷智能科技有限公司创始之一,目前合作公司富士康、歌尔等几家新能源公司
如果文章对你有帮助,欢迎关注、点赞、收藏(一键三连)和C#、Halcon、python+opencv、VUE、各大公司面试等一些订阅专栏哦
有任何问题欢迎私信,看到会及时回复
关注苏州程序大白,分享粉丝福利
前言
文本读取在上位机开发中经常会使用到,实现的方式也有很多种,今天跟大家分享一下C#实现读取读取的7种方式。
这里我们先写好了一个测试界面,提供一个文件路径选择的入口,具体如下所示:

第一个方式
基于FileStream,并结合它的Read方法读取指定的字节数组,最后转换成字符串进行显示。
this.rtb_Content.Clear(); FileStream fs = new FileStream(this.txt_FilePath.Text, FileMode.Open, FileAccess.Read); int n = (int)fs.Length; byte[] b = new byte[n]; int r = fs.Read(b, 0, n); fs.Close(); this.rtb_Content.Text = Encoding.UTF8.GetString(b, 0, n);
第二个方式
基于FileStream,一个字节``一个字节读取,放到字节数组中,最后转换成字符串进行显示。
this.rtb_Content.Clear(); FileStream fs = new FileStream(this.txt_FilePath.Text, FileMode.Open, FileAccess.Read); long n = fs.Length; byte[] b = new byte[n]; int data, index; index = 0; data = fs.ReadByte(); while (data != -1) { b[index++] = Convert.ToByte(data); data = fs.ReadByte(); } fs.Close(); this.rtb_Content.Text = Encoding.UTF8.GetString(b);
第三个方式
基于File类,直接全部读取出来并显示。
this.rtb_Content.Clear();this.rtb_Content.Text = File.ReadAllText(this.txt_FilePath.Text, Encoding.UTF8);
第四个方式
基于StreamReader,一行一行读取,最后拼接并显示。
this.rtb_Content.Clear(); StreamReader sr = new StreamReader(this.txt_FilePath.Text, Encoding.UTF8); string line = sr.ReadLine(); while (line != null) { this.rtb_Content.AppendText(line); line = sr.ReadLine(); if (line != null) { this.rtb_Content.AppendText("\r\n"); } } sr.Close();
第五个方式
基于StreamReader,一次性读取到结尾,最后显示。
this.rtb_Content.Clear(); StreamReader sr = new StreamReader(this.txt_FilePath.Text, Encoding.UTF8); this.rtb_Content.Text = sr.ReadToEnd(); sr.Close();
第六个方式
基于StreamReader,一行一行读取,通过EndOfSteam判断是否到结尾,最后拼接并显示。
this.rtb_Content.Clear(); StreamReader sr = new StreamReader(this.txt_FilePath.Text, Encoding.UTF8); while (!sr.EndOfStream) { this.rtb_Content.AppendText(sr.ReadLine()); if (!sr.EndOfStream) { this.rtb_Content.AppendText("\r\n"); } } sr.Close();
第七个方式
基于FileStream和StreamReader来实现。
this.rtb_Content.Clear(); FileStream fs = new FileStream(this.txt_FilePath.Text, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs, Encoding.UTF8); this.rtb_Content.Text = sr.ReadToEnd(); fs.Close(); sr.Close();
经过测试,以上每个方法都可以实现文本文件的读取。

以上7种方式主要是分别基于FileStream、File和StreamReader这三种来实现的,这三种方式的区别在于:
-
FileStream类可以对任意类型的文件进行读取操作,而且我们也可以按照需要指定每一次读取字节长度,以此减少内存的消耗,提高读取效率。 -
StreamReader的特点是,它只能对文本文件进行读写操作,可以一行一行的写入和读取。 -
File类它是一个静态类,当我们查看file类的那些静态方法时,我们可以发现,在这个类里面的方法封装了可以执行文件读写操作的对象,例如:Filestream,StreamReader,我们通过File去执行任何文件的读写操作时,实际上是使用FileStream或SteamReader对象来执行文件的读写操作,代码如下所示:
public static string ReadAllText(string path, Encoding encoding) { if (path == null) { throw new ArgumentNullException("path"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (path.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); } return InternalReadAllText(path, encoding, checkHost: true); } private static string InternalReadAllText(string path, Encoding encoding, bool checkHost) { using (StreamReader streamReader = new StreamReader(path, encoding, detectEncodingFromByteOrderMarks: true, StreamReader.DefaultBufferSize, checkHost)) { return streamReader.ReadToEnd(); } }
版权声明
本文为[华为云]所创,转载请带上原文链接,感谢
https://bbs.huaweicloud.com/blogs/348933
边栏推荐
- sublime主题配色
- 【软件测试系列十二】《压力测试报告模板》
- 【软件测试系列六】《软件系统测试方案》
- Detailed explanation of kubernetes (II) -- kubernetes structure and resource object
- Using lazy deletion and scheduled deletion to realize expired localstorage cache
- The small program rotates the mobile phone to push the stream, and the remote pull stream picture is cut
- [software test series vi] software system test scheme
- Is it safe to open an account for stock speculation
- ASP. Net core to realize JWT authorization and authentication (1. Theory)
- 上海疫情中,新消费品牌们的坚守、放弃与救赎
猜你喜欢

The simpler the Oracle database machine is, the more reliable it is. Oracle buried the "colored egg" 11 years ago

“如何实现集中管理、灵活高效的CI/CD”在线研讨会精彩内容分享

一分钟教会您使用Yolov5训练自己的数据集并测试

China Resources Yibao is rumored to have an IPO, and nongnongshanquan may usher in an early "old enemy"
![[dark horse morning post] Tao Hong paid 260 million dividends from Zhangting MLM company in three years; Yiling pharmaceutical replied to Lianhua Qingwen dispute: the case has been reported; Tencent v](/img/d7/4671b5a74317a8f87ffd36be2b34e1.jpg)
[dark horse morning post] Tao Hong paid 260 million dividends from Zhangting MLM company in three years; Yiling pharmaceutical replied to Lianhua Qingwen dispute: the case has been reported; Tencent v

Static and non-static construction method of parent-child class loading order

Live broadcast of changes in the Jianghu: Li Jiaqi is trapped in a luxury house, Luo Yonghao fades out, and Weiya Sydney helps broadcast it

World Reading Day | recommended books list of database classic books (free message at the end of the text)

The persistence, abandonment and redemption of new consumer brands in the Shanghai epidemic

海量数据2021年创收4.21亿元,数据库产品毛利率提升8.78%!
随机推荐
【软件测试系列二】《软件测试流程规范》
[software test series Xi] stress test scenario and test case template
二进制文件版本控制工具选择难?看完这篇你会找到答案
Usage Summary of hiredis and rapidjson Libraries
去中心化VC平台CULTDAO发起对BetaMars项目投票,目前投票正在进行中
One day, Alibaba database will squeeze Oracle out of the market
【软件测试系列六】《软件系统测试方案》
基于pytorch搭建VGGNet神经网络用于花类识别
a标签或者<router-link>使用target=“_blank“打开新页面,新页面的sessionStorage丢失
Yyds dry goods inventory a common error in a web crawler
DR-AP6018-A-wifi6-Access-Point-Qualcomm-IPQ6010-2T2R-2.5G-ETH-port-supporting-5G-celluar-Modem-aluminum-body.
Integration announcement keyfi is now online moonbeam
达梦数据库市场份额增速行业领先,盈利能力大幅提升
Scala安装和开发环境配置教程
精彩联动!OpenMLDB Pulsar Connector原理和实操
[Software Testing Series IV] "test points to be paid attention to in software testing"
The market share growth rate of Dameng database is leading in the industry, and its profitability has been greatly improved
顶流“健身博主”刘畊宏
Who does the team listen to
Sublime theme colors