隔離儲存區提供以組件/網域/使用者為範圍的虛擬檔案系統,無需管理實體路徑、權限自動隔離,適合儲存使用者偏好設定、暫存資料、小型本地快取。資料實際儲存在 %LocalAppData%\IsolatedStorage 下,自動處理跨使用者隔離。
static void UserIsolationFile() {
// 取得當前應用程式域的隔離存放區
using (var store = IsolatedStorageFile.GetUserStoreForDomain()) {
// 寫入
using (var stream = new IsolatedStorageFileStream("storagefile.txt", FileMode.Create, FileAccess.Write, store))
using (var writer = new StreamWriter(stream)) {
writer.WriteLine("You are dead!");
}
// 列舉檔案
string[] files = store.GetFileNames("storagefile.txt");
foreach (var file in files) {
// 讀取
using (var stream = new IsolatedStorageFileStream(file, FileMode.Open, store))
using (var reader = new StreamReader(stream)) {
Console.WriteLine(reader.ReadToEnd());
}
}
}
Console.ReadKey();
}
MemoryMappedFile 將檔案內容映射至進程虛擬記憶體,透過指標直接讀寫,避免繼續的 Read/Write 系統呼叫開銷。適用於:大型日誌檔分析、共享記憶體進程間通訊 (IPC)、隨機存取巨大資料集。作業系統自動處理分頁調度,只載入被存取的頁面。
static void MappingMemory() {
// 建立 1MB 對應檔
using (var mmf = MemoryMappedFile.CreateFromFile(
@"d:\mappingmemory.txt", FileMode.Create, "fileHandle", 1024 * 1024)) {
string valueToWrite = "Written to the mapped-memory file on " + DateTime.Now;
var accessor = mmf.CreateViewAccessor();
// 寫入位元組陣列
byte[] data = Encoding.ASCII.GetBytes(valueToWrite);
accessor.WriteArray(0, data, 0, data.Length);
// 讀回驗證
var readOut = new byte[data.Length];
accessor.ReadArray(0, readOut, 0, readOut.Length);
Console.WriteLine("The data is: " + Encoding.ASCII.GetString(readOut));
}
Console.ReadKey();
}
// 進程 A 建立具名共享記憶體
using (var mmf = MemoryMappedFile.CreateNew("SharedData", 4096)) {
using (var accessor = mmf.CreateViewAccessor()) {
accessor.Write(0, 12345);
Console.WriteLine("Process A wrote 12345. Press any key to exit...");
Console.ReadKey();
}
}
// 進程 B 開啟同名共享記憶體
using (var mmf = MemoryMappedFile.OpenExisting("SharedData")) {
using (var accessor = mmf.CreateViewAccessor()) {
int value = accessor.ReadInt32(0);
Console.WriteLine("Process B read: " + value);
}
}
| 特性 | 隔離儲存區 | 記憶體對應檔 |
|---|---|---|
| 適用資料量 | 小型 (KB~MB) | 大型 (MB~GB) |
| 隨機存取 | 需串流定位 | 原生支援 (指標/ViewAccessor) |
| 跨進程共享 | 不支援 | 支援 (具名 MMF) |
| 權限隔離 | 自動 (使用者/組件/網域) | 需自行控制 ACL |
| 持久化 | 自動 | 需手動 Flush/建立檔案對應 |
ViewAccessor.SafeMemoryMappedViewHandle 進行非結構化資料存取;大檔案分段建立 View (CreateViewAccessor(offset, size)) 降低虛擬記憶體壓力。IsolatedStorageException、IOException (磁碟滿)、UnauthorizedAccessException 皆需捕捉處理。