MemoryStream.SetLength(Int64) 方法


将当前流的长度设为指定值。Sets the length of the current stream to the specified value.

 override void SetLength(long value);
public override void SetLength (long value);
override this.SetLength : int64 -> unit
Public Overrides Sub SetLength (value As Long)



用于设置长度的值。The value at which to set the length.


当前流无法调整大小,而且 value 大于当前容量。The current stream is not resizable and value is larger than the current capacity.

- 或 --or- 当前流不支持写入。The current stream does not support writing.

value 为负或者大于 MemoryStream 的最大长度,其中最大长度为 (MaxValue- origin),origin 为基础缓冲区中作为流的起点的索引。value is negative or is greater than the maximum length of the MemoryStream, where the maximum length is(MaxValue - origin), and origin is the index into the underlying buffer at which the stream starts.


此方法重写 SetLengthThis method overrides SetLength.

如果指定的值小于流的当前长度,则流将被截断。If the specified value is less than the current length of the stream, the stream is truncated. 如果在截断后,流中的当前位置超过了流的结尾,则 ReadByte 方法返回-1,Read 方法会将零字节读入提供的字节数组,WriteWriteByte 方法会在流的末尾追加指定的字节,增加其长度。If after the truncation the current position within the stream is past the end of the stream, the ReadByte method returns -1, the Read method reads zero bytes into the provided byte array, and Write and WriteByte methods append specified bytes at the end of the stream, increasing its length. 如果指定的值大于当前容量并且流的大小可调整,则会增加容量,并保持流中的当前位置不变。If the specified value is larger than the current capacity and the stream is resizable, the capacity is increased, and the current position within the stream is unchanged. 如果增加长度,则新旧长度之间的流的内容将初始化为零。If the length is increased, the contents of the stream between the old and the new length are initialized to zeros.


MemoryStream 实例必须支持编写此方法才能工作。A MemoryStream instance must support writing for this method to work. 使用 CanWrite 属性可确定当前实例是否支持写入。Use the CanWrite property to determine whether the current instance supports writing. 有关附加信息,请参见 CanWriteFor additional information, see CanWrite.