FileStreamOptions.PreallocationSize 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
public:
property long PreallocationSize { long get(); void set(long value); };
public long PreallocationSize { get; set; }
member this.PreallocationSize : int64 with get, set
Public Property PreallocationSize As Long
屬性值
一個非負數,代表檔案初始分配大小(以位元組為單位)。
例外狀況
value 為負數。
範例
以下程式碼範例示範如何在處理FileStream物件時使用PreallocationSize:
using System.IO;
public static class PreallocationSizeExample
{
public static void Main()
{
string destinationPath = "destination.dll";
var openForReading = new FileStreamOptions { Mode = FileMode.Open };
using var source = new FileStream(typeof(PreallocationSizeExample).Assembly.Location, openForReading);
var createForWriting = new FileStreamOptions
{
Mode = FileMode.CreateNew,
Access = FileAccess.Write,
PreallocationSize = source.Length // specify size up-front
};
using var destination = new FileStream(destinationPath, createForWriting);
source.CopyTo(destination); // copies the contents of the assembly file into the destination file
}
}
Imports System.IO
Module PreallocationSizeExample
Sub Main()
Dim destinationPath As String = "destination.dll"
Dim openForReading = New FileStreamOptions With {
.Mode = FileMode.Open
}
Using source = New FileStream(GetType(PreallocationSizeExample).Assembly.Location, openForReading)
Dim createForWriting = New FileStreamOptions With {
.Mode = FileMode.CreateNew,
.Access = FileAccess.Write,
.PreallocationSize = source.Length ' specify size up-front
}
Using destination = New FileStream(destinationPath, createForWriting)
source.CopyTo(destination) ' copies the contents of the assembly file into the destination file
End Using
End Using
End Sub
End Module
備註
PreallocationSize 只能在寫入模式Access 請求(必須設定為 Write),以及在建立新檔案時(Mode 必須設定為 Create 或 CreateNew)。 否則, FileStream 建構子會拋出例外。
若作業系統、平台或檔案系統不支援預配置,則 PreallocationSize 會被忽略。 這正是 Web Assembly(WASM)和 FreeBSD 的情況。
若磁碟空間不足或檔案系統不支援指定大小的檔案(例如:FAT32 上的 5 GB 檔案),則會拋出例外。
檔案長度由寫入檔案的位元組數決定。
當檔案關閉且未寫入所有分配空間時,剩餘空間的處理方式取決於平台。 在 Windows 上,這個空間不再保留給該檔案。 在其他平台,如 Linux 和 macOS,則仍分配給檔案。
舉例來說,假設一個檔案預先分配了 2 GB,但只寫入了 1 GB。 關閉檔案後,所有作業系統的檔案長度為 1 GB。 在 Windows 上,分配大小也是 1 GB,但在 Linux 和 macOS 上,分配大小仍然是 2 GB。
寫超過原本預定的部分是被允許的。 只要磁碟空間足夠,操作應該會成功。