基于C#實(shí)現(xiàn)文本讀取的常用方式詳解
前言
文本讀取在上位機(jī)開發(fā)中經(jīng)常會(huì)使用到,實(shí)現(xiàn)的方式也有很多種,今天跟大家分享一下C#實(shí)現(xiàn)讀取文本的7種方式。
這里我們先寫好了一個(gè)測(cè)試界面,提供一個(gè)文件路徑選擇的入口,具體如下所示:

方式一
基于FileStream,并結(jié)合它的Read方法讀取指定的字節(jié)數(shù)組,最后轉(zhuǎn)換成字符串進(jìn)行顯示。
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,一次性讀取到結(jié)尾,最后顯示。
this.rtb_Content.Clear();
StreamReader sr = new StreamReader(this.txt_FilePath.Text, Encoding.UTF8);
this.rtb_Content.Text = sr.ReadToEnd();
sr.Close();
方式六
基于StreamReader,一行一行讀取,通過EndOfSteam判斷是否到結(jié)尾,最后拼接并顯示。
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來實(shí)現(xiàn)。
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();
總結(jié)
以上7種方式主要是分別基于FileStream、File和StreamReader這三種來實(shí)現(xiàn)的,這三種方式的區(qū)別在于:
FileStream類可以對(duì)任意類型的文件進(jìn)行讀取操作,而且我們也可以按照需要指定每一次讀取字節(jié)長(zhǎng)度,以此減少內(nèi)存的消耗,提高讀取效率。
StreamReader的特點(diǎn)是,它只能對(duì)文本文件進(jìn)行讀寫操作,可以一行一行的寫入和讀取。
File類它是一個(gè)靜態(tài)類,當(dāng)我們查看file類的那些靜態(tài)方法時(shí),我們可以發(fā)現(xiàn),在這個(gè)類里面的方法封裝了可以執(zhí)行文件讀寫操作的對(duì)象,例如:Filestream,StreamReader,我們通過File去執(zhí)行任何文件的讀寫操作時(shí),實(shí)際上是使用FileStream或SteamReader對(duì)象來執(zhí)行文件的讀寫操作,代碼如下所示:
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();
}
}
方法補(bǔ)充
在 C# 中讀取文本文件有多種方式,每種方式適用于不同的場(chǎng)景。下面從簡(jiǎn)單到復(fù)雜,介紹最常用的方法,并提供代碼示例和選型建議。
快速選擇(速查表)
| 需求 | 推薦方法 | 代碼量 | 內(nèi)存占用 | 適用場(chǎng)景 |
|---|---|---|---|---|
| 一次性讀取整個(gè)文件 | File.ReadAllText | 極少 | 高(整個(gè)文件) | 小文件(< 10 MB) |
| 按行讀入數(shù)組 | File.ReadAllLines | 極少 | 高 | 小文件,需要每行獨(dú)立處理 |
| 逐行處理(不占內(nèi)存) | File.ReadLines | 少 | 低(流式) | 大文件,逐行處理 |
| 手動(dòng)控制編碼/緩沖 | StreamReader | 中等 | 可控 | 需要精細(xì)控制讀取過程 |
| 異步讀?。ú蛔枞鸘I) | StreamReader.ReadToEndAsync | 中等 | 高 | WinForm/WPF 等需要保持界面響應(yīng) |
| 讀取大型文件并解析 | StreamReader.ReadLine + 循環(huán) | 中等 | 低 | 超大日志文件、CSV 解析等 |
1. 最簡(jiǎn)單:File.ReadAllText —— 一次讀取全部文本
using System.IO;
string content = File.ReadAllText("file.txt", Encoding.UTF8);
Console.WriteLine(content);特點(diǎn):代碼最簡(jiǎn)潔,直接將文件內(nèi)容讀入一個(gè)字符串。適合小文件,大文件會(huì)消耗大量?jī)?nèi)存。
可選編碼參數(shù):Encoding.UTF8, Encoding.Default, Encoding.ASCII 等。
2. 按行讀取為數(shù)組:File.ReadAllLines
string[] lines = File.ReadAllLines("file.txt", Encoding.UTF8);
foreach (string line in lines)
{
Console.WriteLine(line);
}特點(diǎn):返回字符串?dāng)?shù)組,每行一個(gè)元素。同樣適合小文件。
3. 逐行流式讀取:File.ReadLines —— 推薦處理大文件
foreach (string line in File.ReadLines("file.txt", Encoding.UTF8))
{
Console.WriteLine(line);
// 處理每行,不會(huì)一次性加載整個(gè)文件
}特點(diǎn):返回 IEnumerable<string>,使用 yield 實(shí)現(xiàn)延遲執(zhí)行,內(nèi)存效率極高。推薦用于任何大小的文本文件。
4. 手動(dòng)流式讀取:StreamReader(更精細(xì)控制)
using (StreamReader reader = new StreamReader("file.txt", Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
// 若需一次性讀到底:string all = reader.ReadToEnd();
}特點(diǎn):可以控制緩沖區(qū)大小、位置(BaseStream.Seek)等。適合需要自定義解析邏輯的場(chǎng)景。
5. 異步讀?。╓inForm/WPF/ASP.NET Core 中保持響應(yīng))
using (StreamReader reader = new StreamReader("file.txt", Encoding.UTF8))
{
string content = await reader.ReadToEndAsync();
// 或 async 逐行:
// while ((line = await reader.ReadLineAsync()) != null) { ... }
}特點(diǎn):異步方法不會(huì)阻塞調(diào)用線程,適合 UI 程序或高并發(fā)服務(wù)器端。
6. 讀取指定編碼的文件(如 GB2312)
// 需注冊(cè)編碼提供程序(.NET Core 需額外添加)
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding gb2312 = Encoding.GetEncoding("GB2312");
string content = File.ReadAllText("gbk_file.txt", gb2312);注意:.NET Core/.NET 5+ 默認(rèn)不支持 GB18030 等擴(kuò)展編碼,需添加 System.Text.Encoding.CodePages 包。
性能與內(nèi)存對(duì)比
| 方法 | 內(nèi)存峰值 | 適用文件大小 | 讀取速度(小文件) | 讀取速度(大文件) |
|---|---|---|---|---|
ReadAllText | 文件大小的 2~3 倍 | < 50 MB | 快 | 極慢/可能 OOM |
ReadAllLines | 文件大小的 ~2 倍 + 每行對(duì)象開銷 | < 50 MB | 較快 | 慢/可能 OOM |
ReadLines | O(1)(只緩存當(dāng)前行) | 不限 | 中等(需迭代) | 快(流式) |
StreamReader.ReadLine | O(1) | 不限 | 中等 | 快 |
結(jié)論:處理超過 100 MB 的大文件,務(wù)必使用 File.ReadLines 或 StreamReader。
到此這篇關(guān)于基于C#實(shí)現(xiàn)文本讀取的常用方式詳解的文章就介紹到這了,更多相關(guān)C#文本讀取內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)給DataGrid單元行添加雙擊事件的方法
這篇文章主要介紹了C#實(shí)現(xiàn)給DataGrid單元行添加雙擊事件的方法,較為詳細(xì)的分析了C#給DataGrid單元添加雙擊事件的步驟及相關(guān)實(shí)現(xiàn)代碼,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
C#中實(shí)現(xiàn)Json序列化與反序列化的幾種方式
C#中實(shí)現(xiàn)Json的序列化與反序列化也算是個(gè)老話題,那么在這篇文章中我們將老話重提,本文中將會(huì)學(xué)到如何使用C#,來序列化對(duì)象成為Json格式的數(shù)據(jù),以及如何反序列化Json數(shù)據(jù)到對(duì)象。有需要的朋友們可以參考借鑒,下面來跟著小編一起學(xué)習(xí)學(xué)習(xí)吧。2016-12-12
C#中的XML與JSON數(shù)據(jù)處理的案例詳解
在現(xiàn)代軟件開發(fā)中,數(shù)據(jù)交換和存儲(chǔ)的需求日益增長(zhǎng),而 XML 和 JSON 成為了兩種最常用的數(shù)據(jù)格式,它們各有特點(diǎn),在不同的場(chǎng)景下有著各自的優(yōu)勢(shì),本文將從 C# 的角度出發(fā),探討如何處理這兩種數(shù)據(jù)格式,并分享一些常見的問題及解決方法,需要的朋友可以參考下2024-09-09

