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

การใช้ C# FileStream Class

FileStream Class ใน C#

FileStream ให้ Stream สำหรับอ่าน/เขียนไฟล์ในระดับ Byte รองรับ Both Synchronous และ Asynchronous Operations อยู่ใน System.IO

Constructor สำคัญ


// พื้นฐาน
new FileStream(path, FileMode)

// พร้อม Access และ Share
new FileStream(path, FileMode, FileAccess, FileShare)

// Async (แนะนำสำหรับ I/O Bound)
new FileStream(path, FileMode, FileAccess, FileShare, bufferSize, useAsync: true)

FileMode Enum

Modeพฤติกรรม
CreateNewสร้างใหม่, Error ถ้ามีอยู่แล้ว
Createสร้างใหม่, Overwrite ถ้ามีอยู่แล้ว
Openเปิดไฟล์ที่มีอยู่, Error ถ้าไม่มี
OpenOrCreateเปิดถ้ามี, สร้างใหม่ถ้าไม่มี
Truncateเปิดและ Clear เนื้อหา (ต้องมีอยู่)
Appendเปิดและ Seek ไปท้ายไฟล์

ตัวอย่าง: เขียนและอ่าน Byte


using System;
using System.IO;

public class Demo
{
    public static void Main(string[] args)
    {
        string path = @"d:\new.txt";
        
        // เขียน
        using (FileStream fs = new FileStream(path, FileMode.Create))
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello FileStream!");
            fs.Write(data, 0, data.Length);
            // หรือ fs.WriteByte(65); // เขียน Byte เดียว
        }
        
        // อ่าน
        using (FileStream fs = new FileStream(path, FileMode.Open))
        {
            byte[] buffer = new byte[fs.Length];
            int bytesRead = fs.Read(buffer, 0, buffer.Length);
            string text = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine($"Read: {text}");
        }
    }
}

Async Version (แนะนำสำหรับ Production)


public static async Task WriteAsync(string path, string text)
{
    byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true))
    {
        await fs.WriteAsync(data, 0, data.Length);
    }
}

public static async Task ReadAsync(string path)
{
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
    {
        byte[] buffer = new byte[fs.Length];
        await fs.ReadAsync(buffer, 0, buffer.Length);
        return System.Text.Encoding.UTF8.GetString(buffer);
    }
}

Seek และ Position


fs.Seek(0, SeekOrigin.Begin);   // ไปต้นไฟล์
fs.Seek(0, SeekOrigin.End);     // ไปท้ายไฟล์
fs.Seek(10, SeekOrigin.Current); // เลื่อน 10 Byte จากตำแหน่งปัจจุบัน
long pos = fs.Position;         // ตำแหน่งปัจจุบัน

Best Practices

  • ใช้ using หรือ await using (C# 8+) เพื่อ Dispose อัตโนมัติ
  • ใช้ FileStream ตรงๆ เมื่อต้องการ Control ระดับ Byte/Performance
  • งานทั่วไป: ใช้ File.ReadAllText, File.WriteAllBytes, StreamReader/Writer แทน (ง่ายกว่า)
  • Buffer Size: 4096 (4KB) เป็น Default ที่ดี