มีหลายวิธีในการอ่านไฟล์ข้อความทีละบรรทัด ซึ่งรวมถึงStreamReader.ReadLine, File.ReadLines เป็นต้น ให้เราพิจารณาไฟล์ข้อความที่มีอยู่ในเครื่องของเราซึ่งมีบรรทัดดังนี้

การใช้ StreamReader.ReadLine -
C # StreamReader ใช้เพื่ออ่านอักขระไปยังสตรีมในวิธีการเข้ารหัสที่ระบุ StreamReader.Read อ่านอักขระถัดไปหรือชุดอักขระถัดไปจากสตรีมอินพุต StreamReader สืบทอดมาจาก TextReader ซึ่งมีวิธีการอ่านอักขระ บล็อก เส้น หรือเนื้อหาทั้งหมด
ตัวอย่าง
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();
}
}
} ผลลัพธ์
Hi All!! Hello Everyone!! How are you?
การใช้ File.ReadLines
File.ReadAllLines() วิธีการเปิดไฟล์ข้อความ อ่านบรรทัดทั้งหมดของไฟล์เป็น aIEnumerable
ตัวอย่าง
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();
}
}
} ผลลัพธ์
Hi All!! Hello Everyone!! How are you?
การใช้ File.ReadAllLines
สิ่งนี้คล้ายกับ ReadLines มาก อย่างไรก็ตาม มันส่งกลับ String[] และไม่ใช่ anIEnumerable
ตัวอย่าง
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 += 1){
var line = lines[i];
Console.WriteLine(line);
}
Console.ReadLine();
}
}
} ผลลัพธ์
Hi All!! Hello Everyone!! How are you?