FileStreamOptions.PreallocationSize 属性    
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
public:
 property long PreallocationSize { long get(); void set(long value); };public long PreallocationSize { get; set; }member this.PreallocationSize : int64 with get, setPublic Property PreallocationSize As Long属性值
一个非负数,表示文件的初始分配大小(以字节为单位)。
例外
当 为负值时 value 。
示例
下面的代码示例演示如何在处理 对象时使用PreallocationSizeFileStream:
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。
允许写入的内容超过最初预先分配的内容。 只要有足够的磁盘空间,该操作就应成功。