มีหลายวิธีในการอ่าน Text File บรรทัดต่อบรรทัด ได้แก่ StreamReader.ReadLine, File.ReadLines ฯลฯ สมมติมี Text File ในเครื่องมีเนื้อหาดังนี้:
1. ใช้ StreamReader.ReadLine
C# StreamReader ใช้สำหรับอ่าน Characters จาก Stream ใน Encoding ที่ระบุ StreamReader.Read Method อ่าน Character ถัดไปหรือชุด Characters ถัดไปจาก Input Stream StreamReader สืบทอดจาก TextReader ที่จัดเตรียม Methods สำหรับอ่าน Character, Block, Line หรือ All Content
using System;
using System.IO;
using System.Text;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
using (var fileStream = File.OpenRead(@"D:\Demo\Demo.txt"))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) {
string line;
while ((line = streamReader.ReadLine()) != null) {
Console.WriteLine(line);
}
}
Console.ReadLine();
}
}
}
Output
Hi All!!
Hello Everyone!!
How are you?
2. ใช้ File.ReadLines (แนะนำสำหรับไฟล์ใหญ่)
เมธอด File.ReadLines() เปิด Text File อ่านทุกบรรทัดเข้าไปใน IEnumerable<string> แล้วปิดไฟล์ สำคัญ: มันไม่โหลดไฟล์ทั้งหมดเข้า Memory เหมือน ReadAllLines ใช้ Lazy Evaluation (Yield Return)
using System;
using System.IO;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
var lines = File.ReadLines(@"D:\Demo\Demo.txt");
foreach (var line in lines) {
Console.WriteLine(line);
}
Console.ReadLine();
}
}
}
Output
Hi All!!
Hello Everyone!!
How are you?
3. ใช้ File.ReadAllLines
คล้าย ReadLines แต่ Return string[] แทน IEnumerable<String> ทำให้ Random Access ได้ (เข้าถึงบรรทัดไหนก็ได้โดย Index) โหลดไฟล์ทั้งหมดเข้า Memory
using System;
using System.IO;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
var lines = File.ReadAllLines(@"D:\Demo\Demo.txt");
for (var i = 0; i < lines.Length; i++) {
var line = lines[i];
Console.WriteLine(line);
}
Console.ReadLine();
}
}
}
Output
Hi All!!
Hello Everyone!!
How are you?
เปรียบเทียบประสิทธิภาพ
| Method | Memory Usage | Speed (Small File) | Speed (Large File) | Random Access |
|---|---|---|---|---|
StreamReader.ReadLine | ต่ำมาก | เร็ว | เร็วที่สุด | ไม่ได้ (Sequential) |
File.ReadLines | ต่ำมาก (Lazy) | เร็ว | เร็วมาก | ไม่ได้ (Sequential) |
File.ReadAllLines | สูง (โหลดทั้งไฟล์) | เร็วที่สุด | ช้า / OutOfMemory | ได้ (Index-based) |
คำแนะนำ
- ไฟล์เล็ก (< 10MB):
File.ReadAllLinesสะดวกที่สุด - ไฟล์ใหญ่ (> 100MB):
File.ReadLinesหรือStreamReader(Streaming) - ต้องการ Processing แบบ Parallel:
File.ReadLines+AsParallel() - Encoding ไม่ใช่ UTF-8: ใช้
StreamReaderระบุ Encoding
ตัวอย่าง Async (Modern .NET)
using System;
using System.IO;
using System.Threading.Tasks;
public async Task ProcessLargeFileAsync(string filePath) {
using var reader = new StreamReader(filePath);
string line;
while ((line = await reader.ReadLineAsync()) != null) {
// Process line asynchronously
await ProcessLineAsync(line);
}
}