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
| Mode | Behavior |
| 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)
| Share | Allow Others |
| None | Exclusive Lock (Default) |
| Read | Allow Read |
| Write | Allow Write |
| ReadWrite | Allow Read/Write |
| Delete | Allow Delete |
| Inheritable | Handle 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 (แนะนำสำหรับงานทั่วไป)
| Task | High-Level API |
| Read All Text | File.ReadAllText / ReadAllTextAsync |
| Read Lines | File.ReadAllLines / ReadLines / ReadLinesAsync |
| Write Text | File.WriteAllText / WriteAllTextAsync / AppendAllText |
| Read All Bytes | File.ReadAllBytes / ReadAllBytesAsync |
| Write Bytes | File.WriteAllBytes / WriteAllBytesAsync |
| Copy/Move/Delete | File.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