在 C# 中,高效加載 TXT 文件內容可以通過多種方法實現,具體方法的選擇取決于文件的大小和讀取需求。以下是一些常用的方法:
1. 使用 `File.ReadAllText`
如果文件比較小,并且你希望一行一行地讀取整個內容,可以使用 `File.ReadAllText` 方法:
using System;
using System.IO;
class Program
{
? ? static void Main()
? ? {
? ? ? ? string filePath = "yourfile.txt";
? ? ? ? string content = File.ReadAllText(filePath);
? ? ? ? Console.WriteLine(content);
? ? }
}
2. 使用 `File.ReadAllLines`
如果你想將文件的每一行都作為一個字符串存儲在數組中,可以使用 `File.ReadAllLines`:
using System;
using System.IO;
class Program
{
? ? static void Main()
? ? {
? ? ? ? string filePath = "yourfile.txt";
? ? ? ? string[] lines = File.ReadAllLines(filePath);
? ? ? ??
? ? ? ? foreach (var line in lines)
? ? ? ? {
? ? ? ? ? ? Console.WriteLine(line);
? ? ? ? }
? ? }
}
3. 使用 `StreamReader`
如果你處理的是較大的文件,使用 `StreamReader` 可以逐行讀取,這樣可以節省內存并提高性能:
using System;
using System.IO;
class Program
{
? ? static void Main()
? ? {
? ? ? ? string filePath = "yourfile.txt";
? ? ? ??
? ? ? ? using (StreamReader reader = new StreamReader(filePath))
? ? ? ? {
? ? ? ? ? ? string line;
? ? ? ? ? ? while ((line = reader.ReadLine()) != null)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Console.WriteLine(line);
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
4. 使用 `FileStream` 和 `StreamReader`
對于需要更底層控制的情況,可以使用 `FileStream` 結合 `StreamReader`:
using System;
using System.IO;
class Program
{
? ? static void Main()
? ? {
? ? ? ? string filePath = "yourfile.txt";
? ? ? ? using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
? ? ? ? using (StreamReader reader = new StreamReader(fs))
? ? ? ? {
? ? ? ? ? ? string line;
? ? ? ? ? ? while ((line = reader.ReadLine()) != null)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Console.WriteLine(line);
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
性能考慮
????????對于較小的文件,`File.ReadAllText` 和 `File.ReadAllLines` 方法會非常方便且高效。
????????對于較大的文件,使用 `StreamReader` 是一個更佳的選擇,因為它不會一次性將整個文件讀入內存,而是逐行讀取,避免了內存高峰。
????????如果你需要在讀取時對每一行進行處理,可以結合 `StreamReader` 進行流式處理。
以上是 C# 中高效加載 TXT 文件內容的幾種常見方法,根據您的需求選擇合適的方式即可。
如果您喜歡此文章,請收藏、點贊、評論,謝謝,祝您快樂每一天。?