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 - 原點),原點是資料流開始的基礎緩衝區索引。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.