C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#文本读取

基于C#实现文本读取的常用方式详解

作者:厦门德仔

本文详细介绍了在C#开发中使用七种不同的方式来读取文件,包括FileStream配合Read方法,逐字节读取,File类的ReadAllText,StreamReader逐行读取和一次性读取等,感兴趣的小伙伴可以跟随小编一起学习一下

前言

文本读取在上位机开发中经常会使用到,实现的方式也有很多种,今天跟大家分享一下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);

方式二

            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();
            }
        } 

方法补充

在 C# 中读取文本文件有多种方式,每种方式适用于不同的场景。下面从简单到复杂,介绍最常用的方法,并提供代码示例和选型建议。

快速选择(速查表)

需求推荐方法代码量内存占用适用场景
一次性读取整个文件File.ReadAllText极少高(整个文件)小文件(< 10 MB)
按行读入数组File.ReadAllLines极少小文件,需要每行独立处理
逐行处理(不占内存)File.ReadLines低(流式)大文件,逐行处理
手动控制编码/缓冲StreamReader中等可控需要精细控制读取过程
异步读取(不阻塞UI)StreamReader.ReadToEndAsync中等WinForm/WPF 等需要保持界面响应
读取大型文件并解析StreamReader.ReadLine + 循环中等超大日志文件、CSV 解析等

1. 最简单:File.ReadAllText —— 一次读取全部文本

using System.IO;

string content = File.ReadAllText("file.txt", Encoding.UTF8);
Console.WriteLine(content);

特点:代码最简洁,直接将文件内容读入一个字符串。适合小文件,大文件会消耗大量内存。

可选编码参数Encoding.UTF8Encoding.DefaultEncoding.ASCII 等。

2. 按行读取为数组:File.ReadAllLines

string[] lines = File.ReadAllLines("file.txt", Encoding.UTF8);
foreach (string line in lines)
{
    Console.WriteLine(line);
}

特点:返回字符串数组,每行一个元素。同样适合小文件。

3. 逐行流式读取:File.ReadLines —— 推荐处理大文件

foreach (string line in File.ReadLines("file.txt", Encoding.UTF8))
{
    Console.WriteLine(line);
    // 处理每行,不会一次性加载整个文件
}

特点:返回 IEnumerable<string>,使用 yield 实现延迟执行,内存效率极高。推荐用于任何大小的文本文件。

4. 手动流式读取:StreamReader(更精细控制)

using (StreamReader reader = new StreamReader("file.txt", Encoding.UTF8))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
    // 若需一次性读到底:string all = reader.ReadToEnd();
}

特点:可以控制缓冲区大小、位置(BaseStream.Seek)等。适合需要自定义解析逻辑的场景。

5. 异步读取(WinForm/WPF/ASP.NET Core 中保持响应)

using (StreamReader reader = new StreamReader("file.txt", Encoding.UTF8))
{
    string content = await reader.ReadToEndAsync();
    // 或 async 逐行:
    // while ((line = await reader.ReadLineAsync()) != null) { ... }
}

特点:异步方法不会阻塞调用线程,适合 UI 程序或高并发服务器端。

6. 读取指定编码的文件(如 GB2312)

// 需注册编码提供程序(.NET Core 需额外添加)
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding gb2312 = Encoding.GetEncoding("GB2312");
string content = File.ReadAllText("gbk_file.txt", gb2312);

注意:.NET Core/.NET 5+ 默认不支持 GB18030 等扩展编码,需添加 System.Text.Encoding.CodePages 包。

性能与内存对比

方法内存峰值适用文件大小读取速度(小文件)读取速度(大文件)
ReadAllText文件大小的 2~3 倍< 50 MB极慢/可能 OOM
ReadAllLines文件大小的 ~2 倍 + 每行对象开销< 50 MB较快慢/可能 OOM
ReadLinesO(1)(只缓存当前行)不限中等(需迭代)快(流式)
StreamReader.ReadLineO(1)不限中等

结论:处理超过 100 MB 的大文件,务必使用 File.ReadLines 或 StreamReader

到此这篇关于基于C#实现文本读取的常用方式详解的文章就介绍到这了,更多相关C#文本读取内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文