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

File Objects ใน C# - FileStream, FileMode, FileAccess, FileShare

FileStream เป็น Low-level Stream สำหรับไฟล์ ให้ควบคุมการอ่าน/เขียนแบบ Byte-level ได้เต็มที่

Constructor Parameters


var fs = new FileStream(
    path: "test.dat",
    mode: FileMode.OpenOrCreate,
    access: FileAccess.ReadWrite,
    share: FileShare.None,
    bufferSize: 4096,
    useAsync: false);

FileMode Enum

ModeBehavior
CreateNewสร้างใหม่ - Error ถ้ามีอยู่แล้ว
Createสร้างใหม่ - Overwrite ถ้ามีอยู่แล้ว
Openเปิดที่มีอยู่ - Error ถ้าไม่มี
OpenOrCreateเปิดถ้ามี, สร้างถ้าไม่มี
Truncateเปิดและ Clear Content (Size=0) - Error ถ้าไม่มี
Appendเปิดและ Seek ไปท้าย - สร้างถ้าไม่มี

FileAccess Enum

Accessอ่านเขียน
Read✓✗
Write✗✓
ReadWrite✓✓

FileShare Enum (Concurrency Control)

ShareAllow Others
NoneExclusive Lock (Default)
ReadAllow Read
WriteAllow Write
ReadWriteAllow Read/Write
DeleteAllow Delete
InheritableHandle Inheritable by Child Process

ตัวอย่างครบถ้วน


using System;
using System.IO;

public class FileStreamDemo
{
    public static void Main()
    {
        string path = "test.dat";

        // Write Binary Data
        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            for (int i = 1; i <= 20; i++)
            {
                fs.WriteByte((byte)i);
            }
        }

        // Read Binary Data
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            fs.Position = 0; // Seek to Start

            for (int i = 0; i <= 20; i++)
            {
                int b = fs.ReadByte();
                if (b == -1) break; // End of Stream
                Console.Write(b + " ");
            }
        }
        // Output: 1 2 3 ... 20
    }
}

Position & Seek


using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
    // Position Property
    Console.WriteLine($"Position: {fs.Position}");
    Console.WriteLine($"Length: {fs.Length}");

    // Seek Methods
    fs.Seek(0, SeekOrigin.Begin);   // ไปหน้าไฟล์
    fs.Seek(0, SeekOrigin.End);     // ไปท้ายไฟล์
    fs.Seek(10, SeekOrigin.Current); // หนีบ 10 Bytes จากตำแหน่งปัจจุบัน

    // Read/Write at Position
    fs.Position = 100;
    fs.WriteByte(255);
}

Async Operations (.NET 4.5+)


using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true))
{
    byte[] buffer = new byte[1024];
    int bytesRead = await fs.ReadAsync(buffer, 0, buffer.Length);
    // หรือ .NET 5+
    int bytesRead = await fs.ReadAsync(buffer);
}

High-Level Alternatives (แนะนำสำหรับงานทั่วไป)

TaskHigh-Level API
Read All TextFile.ReadAllText / ReadAllTextAsync
Read LinesFile.ReadAllLines / ReadLines / ReadLinesAsync
Write TextFile.WriteAllText / WriteAllTextAsync / AppendAllText
Read All BytesFile.ReadAllBytes / ReadAllBytesAsync
Write BytesFile.WriteAllBytes / WriteAllBytesAsync
Copy/Move/DeleteFile.Copy, Move, Delete

เมื่อไหร่ใช้ FileStream โดยตรง

  • Random Access (Seek/Position Control)
  • Binary Format Parsing (Custom Protocol)
  • Large File Processing (Streaming + Buffer Control)
  • Concurrent Access Control (FileShare)
  • Memory-mapped Files Alternative