MemoryStream MemoryStream MemoryStream MemoryStream Class

定义

创建其支持存储区为内存的流。Creates a stream whose backing store is memory.

public ref class MemoryStream : System::IO::Stream
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class MemoryStream : System.IO.Stream
type MemoryStream = class
    inherit Stream
Public Class MemoryStream
Inherits Stream
继承
属性

示例

下面的代码示例演示如何读取和写入将内存用作后备存储的数据。The following code example shows how to read and write data using memory as a backing store.

using namespace System;
using namespace System::IO;
using namespace System::Text;

int main()
{
   int count;
   array<Byte>^byteArray;
   array<Char>^charArray;
   UnicodeEncoding^ uniEncoding = gcnew UnicodeEncoding;

   // Create the data to write to the stream.
   array<Byte>^firstString = uniEncoding->GetBytes( "Invalid file path characters are: " );
   array<Byte>^secondString = uniEncoding->GetBytes( Path::InvalidPathChars );

   MemoryStream^ memStream = gcnew MemoryStream( 100 );
   try
   {
      // Write the first string to the stream.
      memStream->Write( firstString, 0, firstString->Length );

      // Write the second string to the stream, byte by byte.
      count = 0;
      while ( count < secondString->Length )
      {
         memStream->WriteByte( secondString[ count++ ] );
      }

      
      // Write the stream properties to the console.
      Console::WriteLine( "Capacity = {0}, Length = {1}, "
      "Position = {2}\n", memStream->Capacity.ToString(), memStream->Length.ToString(), memStream->Position.ToString() );

      // Set the stream position to the beginning of the stream.
      memStream->Seek( 0, SeekOrigin::Begin );

      // Read the first 20 bytes from the stream.
      byteArray = gcnew array<Byte>(memStream->Length);
      count = memStream->Read( byteArray, 0, 20 );

      // Read the remaining bytes, byte by byte.
      while ( count < memStream->Length )
      {
         byteArray[ count++ ] = Convert::ToByte( memStream->ReadByte() );
      }
      
      // Decode the Byte array into a Char array 
      // and write it to the console.
      charArray = gcnew array<Char>(uniEncoding->GetCharCount( byteArray, 0, count ));
      uniEncoding->GetDecoder()->GetChars( byteArray, 0, count, charArray, 0 );
      Console::WriteLine( charArray );
   }
   finally
   {
      memStream->Close();
   }
}
using System;
using System.IO;
using System.Text;

class MemStream
{
    static void Main()
    {
        int count;
        byte[] byteArray;
        char[] charArray;
        UnicodeEncoding uniEncoding = new UnicodeEncoding();

        // Create the data to write to the stream.
        byte[] firstString = uniEncoding.GetBytes(
            "Invalid file path characters are: ");
        byte[] secondString = uniEncoding.GetBytes(
            Path.GetInvalidPathChars());

        using(MemoryStream memStream = new MemoryStream(100))
        {
            // Write the first string to the stream.
            memStream.Write(firstString, 0 , firstString.Length);

            // Write the second string to the stream, byte by byte.
            count = 0;
            while(count < secondString.Length)
            {
                memStream.WriteByte(secondString[count++]);
            }

            // Write the stream properties to the console.
            Console.WriteLine(
                "Capacity = {0}, Length = {1}, Position = {2}\n",
                memStream.Capacity.ToString(),
                memStream.Length.ToString(),
                memStream.Position.ToString());

            // Set the position to the beginning of the stream.
            memStream.Seek(0, SeekOrigin.Begin);

            // Read the first 20 bytes from the stream.
            byteArray = new byte[memStream.Length];
            count = memStream.Read(byteArray, 0, 20);

            // Read the remaining bytes, byte by byte.
            while(count < memStream.Length)
            {
                byteArray[count++] =
                    Convert.ToByte(memStream.ReadByte());
            }

            // Decode the byte array into a char array
            // and write it to the console.
            charArray = new char[uniEncoding.GetCharCount(
                byteArray, 0, count)];
            uniEncoding.GetDecoder().GetChars(
                byteArray, 0, count, charArray, 0);
            Console.WriteLine(charArray);
        }
    }
}
Imports System
Imports System.IO
Imports System.Text

Module MemStream

    Sub Main()
    
        Dim count As Integer
        Dim byteArray As Byte()
        Dim charArray As Char()
        Dim uniEncoding As New UnicodeEncoding()

        ' Create the data to write to the stream.
        Dim firstString As Byte() = _
            uniEncoding.GetBytes("Invalid file path characters are: ")
        Dim secondString As Byte() = _
            uniEncoding.GetBytes(Path.GetInvalidPathChars())

        Dim memStream As New MemoryStream(100)
        Try
            ' Write the first string to the stream.
            memStream.Write(firstString, 0 , firstString.Length)

            ' Write the second string to the stream, byte by byte.
            count = 0
            While(count < secondString.Length)
                memStream.WriteByte(secondString(count))
                count += 1
            End While
            
            ' Write the stream properties to the console.
            Console.WriteLine( _
                "Capacity = {0}, Length = {1}, Position = {2}", _
                memStream.Capacity.ToString(), _
                memStream.Length.ToString(), _
                memStream.Position.ToString())

            ' Set the stream position to the beginning of the stream.
            memStream.Seek(0, SeekOrigin.Begin)

            ' Read the first 20 bytes from the stream.
            byteArray = _
                New Byte(CType(memStream.Length, Integer)){}
            count = memStream.Read(byteArray, 0, 20)

            ' Read the remaining Bytes, Byte by Byte.
            While(count < memStream.Length)
                byteArray(count) = _
                    Convert.ToByte(memStream.ReadByte())
                count += 1
            End While

            ' Decode the Byte array into a Char array 
            ' and write it to the console.
            charArray = _
                New Char(uniEncoding.GetCharCount( _
                byteArray, 0, count)){}
            uniEncoding.GetDecoder().GetChars( _
                byteArray, 0, count, charArray, 0)
            Console.WriteLine(charArray)
        Finally
            memStream.Close()
        End Try

    End Sub
End Module

注解

流的当前位置不在其下一个读取或写入操作的位置可能发生的位置。The current position of a stream is the position at which the next read or write operation could take place. 可以检索当前的位置或通过设置Seek方法。The current position can be retrieved or set through the Seek method. 新实例时MemoryStream创建后,当前位置设置为零。When a new instance of MemoryStream is created, the current position is set to zero.

备注

此类型可实现 IDisposable 接口,但实际上没有任何要释放的资源。This type implements the IDisposable interface, but does not actually have any resources to dispose. 这意味着无需通过直接调用 Dispose() 或使用语言构造(C# 中的 using 或 Visual Basic 中的 Using)对其进行处理。This means that disposing it by directly calling Dispose() or by using a language construct such as using (in C#) or Using (in Visual Basic) is not necessary.

创建与非无符号的字节数组的内存流提供无法调整大小的数据的流。Memory streams created with an unsigned byte array provide a non-resizable stream of the data. 时使用的字节数组,您不能将追加到或缩小流,尽管您可能能够修改的现有内容,具体取决于传递到构造函数的参数。When using a byte array, you can neither append to nor shrink the stream, although you might be able to modify the existing contents depending on the parameters passed into the constructor. 空的内存流大小进行调整,并可以写入以及从中读取。Empty memory streams are resizable, and can be written to and read from.

如果MemoryStream对象添加到 ResX 文件或.resources 文件,请调用GetStream方法在运行时对其进行检索。If a MemoryStream object is added to a ResX file or a .resources file, call the GetStream method at runtime to retrieve it.

如果MemoryStream对象序列化为一个资源文件,它实际上会序列化为UnmanagedMemoryStreamIf a MemoryStream object is serialized to a resource file it will actually be serialized as an UnmanagedMemoryStream. 此行为提供更好的性能,以及能够直接,而无需通过获取对数据指针Stream方法。This behavior provides better performance, as well as the ability to get a pointer to the data directly, without having to go through Stream methods.

构造函数

MemoryStream() MemoryStream() MemoryStream() MemoryStream()

使用初始化为零的可扩展容量初始化 MemoryStream 类的新实例。Initializes a new instance of the MemoryStream class with an expandable capacity initialized to zero.

MemoryStream(Byte[]) MemoryStream(Byte[]) MemoryStream(Byte[]) MemoryStream(Byte[])

基于指定的字节数组初始化 MemoryStream 类的无法调整大小的新实例。Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array.

MemoryStream(Byte[], Boolean) MemoryStream(Byte[], Boolean) MemoryStream(Byte[], Boolean) MemoryStream(Byte[], Boolean)

使用按指定要求设置的 MemoryStream 属性基于指定的字节数组初始化 CanWrite 类的无法调整大小的新实例。Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array with the CanWrite property set as specified.

MemoryStream(Byte[], Int32, Int32) MemoryStream(Byte[], Int32, Int32) MemoryStream(Byte[], Int32, Int32) MemoryStream(Byte[], Int32, Int32)

基于字节数组的指定区域(索引)初始化 MemoryStream 类的无法调整大小的新实例。Initializes a new non-resizable instance of the MemoryStream class based on the specified region (index) of a byte array.

MemoryStream(Byte[], Int32, Int32, Boolean) MemoryStream(Byte[], Int32, Int32, Boolean) MemoryStream(Byte[], Int32, Int32, Boolean) MemoryStream(Byte[], Int32, Int32, Boolean)

使用按指定要求设置的 MemoryStream 属性基于字节数组的指定区域初始化 CanWrite 类的无法调整大小的新实例。Initializes a new non-resizable instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified.

MemoryStream(Byte[], Int32, Int32, Boolean, Boolean) MemoryStream(Byte[], Int32, Int32, Boolean, Boolean) MemoryStream(Byte[], Int32, Int32, Boolean, Boolean) MemoryStream(Byte[], Int32, Int32, Boolean, Boolean)

在按指定要求设置 MemoryStream 属性而且能够调用按指定要求设置的 CanWrite 的情况下,基于字节数组的指定区域初始化 GetBuffer() 类的新实例。Initializes a new instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified, and the ability to call GetBuffer() set as specified.

MemoryStream(Int32) MemoryStream(Int32) MemoryStream(Int32) MemoryStream(Int32)

使用按指定要求初始化的可扩展容量初始化 MemoryStream 类的新实例。Initializes a new instance of the MemoryStream class with an expandable capacity initialized as specified.

属性

CanRead CanRead CanRead CanRead

获取一个值,该值指示当前流是否支持读取。Gets a value indicating whether the current stream supports reading.

CanSeek CanSeek CanSeek CanSeek

获取一个值,该值指示当前流是否支持查找。Gets a value indicating whether the current stream supports seeking.

CanTimeout CanTimeout CanTimeout CanTimeout

获取一个值,该值确定当前流是否可以超时。Gets a value that determines whether the current stream can time out.

(Inherited from Stream)
CanWrite CanWrite CanWrite CanWrite

获取一个值,该值指示当前流是否支持写入。Gets a value indicating whether the current stream supports writing.

Capacity Capacity Capacity Capacity

获取或设置分配给该流的字节数。Gets or sets the number of bytes allocated for this stream.

Length Length Length Length

获取流的长度(以字节为单位)。Gets the length of the stream in bytes.

Position Position Position Position

获取或设置流中的当前位置。Gets or sets the current position within the stream.

ReadTimeout ReadTimeout ReadTimeout ReadTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试读取多长时间。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

(Inherited from Stream)
WriteTimeout WriteTimeout WriteTimeout WriteTimeout

获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试写入多长时间。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(Inherited from Stream)

方法

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)
Close() Close() Close() Close()

关闭读写流。Closes the stream for reading and writing.

CopyTo(Stream) CopyTo(Stream) CopyTo(Stream) CopyTo(Stream)

从当前流中读取字节并将其写入到另一流中。Reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32)
CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream)

从当前流中异步读取字节并将其写入到另一个流中。Asynchronously reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) Inherited from Stream
CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32)

使用指定的缓冲区大小,从当前流中异步读取字节并将其写入到另一流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Inherited from Stream)
CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken)

从当前流中异步读取所有字节并将其写入到另一个流中(使用指定的缓冲区大小和取消令牌)。Asynchronously reads all the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateWaitHandle() CreateWaitHandle() CreateWaitHandle() CreateWaitHandle()

分配 WaitHandle 对象。Allocates a WaitHandle object.

(Inherited from Stream)
Dispose() Dispose() Dispose() Dispose()

释放由 Stream 使用的所有资源。Releases all resources used by the Stream.

(Inherited from Stream)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放 MemoryStream 类使用的非托管资源,并可以选择释放托管资源。Releases the unmanaged resources used by the MemoryStream class and optionally releases the managed resources.

DisposeAsync() DisposeAsync() DisposeAsync() DisposeAsync() Inherited from Stream
EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult)
EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flush() Flush() Flush() Flush()

重写 Flush() 方法以便不执行任何操作。Overrides the Flush() method so that no action is performed.

FlushAsync() FlushAsync() FlushAsync() FlushAsync()

异步清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中。Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Inherited from Stream)
FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken)

异步清除此流的所有缓冲区,并监视取消请求。Asynchronously clears all buffers for this stream, and monitors cancellation requests.

GetBuffer() GetBuffer() GetBuffer() GetBuffer()

返回从其创建此流的无符号字节数组。Returns the array of unsigned bytes from which this stream was created.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ObjectInvariant() ObjectInvariant() ObjectInvariant() ObjectInvariant()

提供对 Contract 的支持。Provides support for a Contract.

Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

从当前流中读取字节块并将数据写入缓冲区中。Reads a block of bytes from the current stream and writes the data to a buffer.

Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>)
ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32)

从当前流异步读取字节序列,并将流中的位置提升读取的字节数。Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Inherited from Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken)

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken)
ReadByte() ReadByte() ReadByte() ReadByte()

从当前流中读取一个字节。Reads a byte from the current stream.

Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin)

将当前流中的位置设置为指定值。Sets the position within the current stream to the specified value.

SetLength(Int64) SetLength(Int64) SetLength(Int64) SetLength(Int64)

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

ToArray() ToArray() ToArray() ToArray()

将流内容写入字节数组,而与 Position 属性无关。Writes the stream contents to a byte array, regardless of the Position property.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
TryGetBuffer(ArraySegment<Byte>) TryGetBuffer(ArraySegment<Byte>) TryGetBuffer(ArraySegment<Byte>) TryGetBuffer(ArraySegment<Byte>)

返回从其创建此流的无符号字节数组。Returns the array of unsigned bytes from which this stream was created. 用于指示转换是否成功的返回值。The return value indicates whether the conversion succeeded.

Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32)

使用从缓冲区读取的数据将字节块写入当前流。Writes a block of bytes to the current stream using data read from a buffer.

Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>)
WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32)

将字节序列异步写入当前流,并将流的当前位置提升写入的字节数。Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(Inherited from Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken)

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)
WriteByte(Byte) WriteByte(Byte) WriteByte(Byte) WriteByte(Byte)

将一个字节写入当前流中的当前位置。Writes a byte to the current stream at the current position.

WriteTo(Stream) WriteTo(Stream) WriteTo(Stream) WriteTo(Stream)

将此内存流的整个内容写入另一个流中。Writes the entire contents of this memory stream to another stream.

显式界面实现

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

释放由 Stream 使用的所有资源。Releases all resources used by the Stream.

(Inherited from Stream)

Extension Methods

AsInputStream(Stream) AsInputStream(Stream) AsInputStream(Stream) AsInputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输入流。Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime.

AsOutputStream(Stream) AsOutputStream(Stream) AsOutputStream(Stream) AsOutputStream(Stream)

将适用于 Windows 应用商店应用的 .NET 中的托管流转换为 Windows 运行时中的输出流。Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime.

AsRandomAccessStream(Stream) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream)

将指定的流转换为随机访问流。Converts the specified stream to a random access stream.

GetWindowsRuntimeBuffer(MemoryStream) GetWindowsRuntimeBuffer(MemoryStream) GetWindowsRuntimeBuffer(MemoryStream) GetWindowsRuntimeBuffer(MemoryStream)
GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32) GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32) GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32) GetWindowsRuntimeBuffer(MemoryStream, Int32, Int32)

适用于

另请参阅