FileStreamOptions.PreallocationSize 屬性

定義

檔案的初始配置大小以位元組為單位。 只有在建立或覆寫一般檔案 (CreateCreateNew) 時,正值才有效。 不允許負值。 在其他情況下, (包括預設 0 值) ,則會予以忽略。 這個值是提示,而且不是強式保證。 Web 元件 (WASM) 不支援它, (忽略此值) 。 針對 Windows、Linux 和 macOS,我們將嘗試預先配置磁碟空間以填滿所要求的配置大小。 如果這發現不可能,作業將會擲回例外狀況。 最終檔案長度 (EOF) 取決於寫入檔案的位元組數目。

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 元件 (WASM) 和 FreeBSD 的情況。

如果磁碟空間不足,或檔案系統不支援指定大小的檔案 (範例:FAT32) 上的 5 GB 檔案,則會擲回例外狀況。

檔案長度取決於寫入檔案的位元組數目。

當檔案關閉,而不是寫入所有已配置的空間時,剩餘空間會發生什麼情況會相依于平臺。 在 Windows 上,此空間不再保留給檔案。 在其他平臺上,例如 Linux 和 macOS,它仍會配置給檔案。

例如,假設檔案預先配置 2 GB,但只會寫入 1 GB。 關閉檔案之後,所有作業系統上的檔案長度為 1 GB。 在 Windows 上,配置的大小也是 1 GB,但在 Linux 和 macOS 上,配置的大小仍為 2 GB。

可以寫入超過最初預先配置的內容。 只要有足夠的磁碟空間,作業應該會成功。

適用於