Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เปิดไฟล์ Text แบบธรรมดาใน C# - StreamReader

การเปิดและอ่านไฟล์ Text แบบธรรมดาใน C# ใช้ StreamReader ร่วมกับ `using` Statement เพื่อจัดการ Resource ให้ถูกต้อง

Basic Pattern (แนะนำ)

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string filePath = @"D:\new.txt";

        try
        {
            // using = Auto Dispose (ปิดไฟล์อัตโนมัติ)
            using (StreamReader sr = new StreamReader(filePath))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"File not found: {filePath}");
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine($"Directory not found: {Path.GetDirectoryName(filePath)}");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine($"Access denied: {filePath}");
        }
        catch (IOException ex)
        {
            Console.WriteLine($"IO Error: {ex.Message}");
        }
    }
}

Modern .NET (C# 8+): Using Declaration


// ไม่ต้องใช้ Braces
using var sr = new StreamReader(filePath);
string line;
while ((line = sr.ReadLine()) != null)
{
    Console.WriteLine(line);
}
// sr.Dispose() เรียกอัตโนมัติที่ End of Scope

อ่านทั้งไฟล์ทีเดียว (ไฟล์เล็ก)


// Sync
string content = File.ReadAllText(filePath);
string[] lines = File.ReadAllLines(filePath);

// Async (.NET 5+)
string content = await File.ReadAllTextAsync(filePath);
string[] lines = await File.ReadAllLinesAsync(filePath);

StreamReader Options


// Encoding
using var sr = new StreamReader(filePath, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);

// Buffer Size (Default 1024, เพิ่มสำหรับไฟล์ใหญ่)
using var sr = new StreamReader(filePath, Encoding.UTF8, true, bufferSize: 65536);

// Leave Stream Open (สำหรับ Stream ที่ Share)
using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
using var sr = new StreamReader(fs, Encoding.UTF8, true, 4096, leaveOpen: true);
// fs ยังเปิดอยู่หลัง sr.Dispose()

Advanced: Peek และ Read Block


using var sr = new StreamReader(filePath);

// Peek: ดู Char ถัดไปโดยไม่ Consume
while (sr.Peek() >= 0)
{
    char c = (char)sr.Read();
    // Process char by char
}

// Read Block: อ่านหลาย Char พร้อมกัน
char[] buffer = new char[4096];
int charsRead;
while ((charsRead = sr.ReadBlock(buffer, 0, buffer.Length)) > 0)
{
    ProcessBuffer(buffer, charsRead);
}

Common Pitfalls

ปัญหาสาเหตุแก้ไข
FileNotFoundExceptionPath ผิด, Relative Path ผิดใช้ Absolute Path, ตรวจสอบ Working Directory
UnauthorizedAccessExceptionPermission, File LockedRun as Admin, Check File Lock
Garbage CharactersEncoding ผิดระบุ Encoding.UTF8 หรือ Detect
OutOfMemoryExceptionReadAllText ไฟล์ใหญ่เกิน RAMใช้ StreamReader / ReadLines แบบ Streaming

File Path Best Practices


// Cross-platform Path
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "data.txt");

// Raw String Literal (C# 11+)
string path = @"D:\Data\file.txt"; // หรือ
string path = "D:\\Data\\file.txt";

// App Context (ASP.NET Core)
string path = Path.Combine(AppContext.BaseDirectory, "data", "config.json");